【问题标题】:Error: "Controller" not found. You need to call "Get.put(Controller())" or Get.lazyPut(()=>Controller())"错误:找不到“控制器”。您需要调用“Get.put(Controller())”或 Get.lazyPut(()=>Controller())”
【发布时间】:2021-12-27 15:59:42
【问题描述】:

我有下一个代码。

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

我不使用 bindings,因为我不使用 GetX 路由/页面并使用自定义选项卡切换。

我的小部件是下一个:

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

【问题讨论】:

  • 您是否在将Get.put 添加到您的main 函数后重新启动应用程序?你不能只是热重载。
  • @Lee3 是的,我完全重启了

标签: flutter dart flutter-getx


【解决方案1】:

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

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

【讨论】:

  • 但是将所有都放入init 而不是我将所有放入main 的方法有什么区别?为什么在我的方法中工作 Get.put(NavigationBarController());Get.put(JobListController()); 得到一个未找到的错误?
  • 为什么这里需要WidgetsFlutterBinding.ensureInitialized();
  • Egh...我按照你写的做了,但得到了同样的错误。也找不到di.init()
  • 需要导入具有init()方法的文件,导入后命名为di 示例:import 'package:/........./dependency_container.dart "作为迪
猜你喜欢
  • 2022-12-16
  • 2021-11-05
  • 2021-09-28
  • 2021-02-26
  • 1970-01-01
  • 2022-11-21
  • 2014-03-15
  • 2016-11-03
  • 2014-01-06
相关资源
最近更新 更多