Error: "Controller" not found. You need to call "Get.put(Controller())" or Get.lazyPut(()=>Controller())"

Error: "Controller" not found. You need to call "Get.put(Controller())" or Get.lazyPut(()=>Controller())"

我有下一个代码。

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

我不使用 bindings 因为我不使用 GetX routes/pages 而使用自定义标签切换。

下一个是我的小部件:

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")),

但是我得到一个错误:

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)

为什么会出现这个错误?导航栏控制器也使用 Get.find 并且工作正常:

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();
  }
}

这里是完整的源代码:https://github.com/bubnenkoff/monitor_client/blob/main/lib/main.dart#L28

您可以创建一个单独的文件以将依赖项注入到该文件中。

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

从 main 调用 init 函数并将 WidgetsFlutterBinding.ensureInitialized() 放在 main 函数的顶部。

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

现在在小部件 class 调用控制器。

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")),