Home > Mobile >  Error: "Controller" not found. You need to call "Get.put(Controller())" or Get.l
Error: "Controller" not found. You need to call "Get.put(Controller())" or Get.l

Time:11-17

I have next code.

main() {
  Get.put(NavigationBarController());
  Get.put(JobListController());
  //...
  runApp(MyApp());
}

I do not use bindings because I do not use GetX routes/pages and use custom tabs-switching.

My widget is next:

class Dashboard extends StatelessWidget {
  var jobCtrl = Get.find<JobListController>();
  
  @override
  Widget build(context) {
    return Container(
      margin: EdgeInsets.only(top: 20.0),
      child: Column(children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            ElevatedButton(
              onPressed: () => jobCtrl.startNewConfigToJob(), child: Text("Run")),

But I am getting an error:

Error: "JobListController" not found. You need to call "Get.put(JobListController())" or "Get.lazyPut(()=>JobListController())"
    at Object.throw_ [as throw] (http://localhost:56854/dart_sdk.js:5374:11)

Why I am getting this error? The Navigation bar Controller is also use Get.find and works fine:

class NavigationBarController extends GetxController {

  get to => Get.find<NavigationBarController>();

  var tabIndex = 0.obs;

  List<Widget> pages = [
      Dashboard(),
      TableStatisticSpeedView()
  ];

 Widget get currentPage => pages[tabIndex.value];

  void changeTabIndex(int index) {
    tabIndex.value = index;
  }

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void dispose() {
    super.dispose();
  }
}

Here is full source code: https://github.com/bubnenkoff/monitor_client/blob/main/lib/main.dart#L28

CodePudding user response:

You can create a separate file for dependency injection into that file put your dependencies.

Future<void> init() async {
Get.put(NavigationBarController());
  Get.put(JobListController());
}

call the init function from main and put WidgetsFlutterBinding.ensureInitialized() at the top of main function.

main() async{
 WidgetsFlutterBinding.ensureInitialized();
 await di.init();
  runApp(MyApp());
}

Now at the widget class call the controller.

class Dashboard extends StatelessWidget {
  var jobCtrl = Get.find<JobListController>();
  
  @override
  Widget build(context) {
    return Container(
      margin: EdgeInsets.only(top: 20.0),
      child: Column(children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            ElevatedButton(
              onPressed: () => jobCtrl.startNewConfigToJob(), child: Text("Run")),
  • Related