已调用Get.put注册JobListController却提示未找到报错原因求解
问题原因及解决方案
报错原因
你的代码初始化顺序出现了逻辑冲突:
- main函数中你先执行
Get.put(NavigationBarController()),再执行Get.put(JobListController()) NavigationBarController初始化时,内部的pages列表会直接创建Dashboard()实例Dashboard类的顶层变量var jobCtrl = Get.find<JobListController>()会在实例化时立即执行,此时JobListController还没有被存入Get容器,因此触发找不到的报错。
而NavigationBarController可以正常使用,是因为你调用Get.find获取它的时机,是在它被put到Get容器之后,不存在顺序冲突。
解决方法
你可以任选以下一种方案修复,建议优先选择前两种结合的方式:
- 方案1:调换依赖注入顺序
将JobListController的注入放在NavigationBarController之前,确保Dashboard实例化时需要的控制器已经提前存入Get容器:
main() { Get.put(JobListController()); Get.put(NavigationBarController()); // 其余代码保持不变 runApp(MyApp()); }
- 方案2:优化控制器的获取时机
不要在类的顶层变量位置直接执行Get.find,避免实例化时提前触发查找逻辑,可以用late修饰实现延迟初始化,或者在使用时再调用查找:
class Dashboard extends StatelessWidget { // 延迟初始化,第一次访问jobCtrl时才执行Get.find late final JobListController jobCtrl = Get.find<JobListController>(); @override Widget build(context) { // 也可以选择在build方法内获取控制器 // final jobCtrl = Get.find<JobListController>(); return Container( margin: EdgeInsets.only(top: 20.0), child: Column(children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ElevatedButton( onPressed: () => jobCtrl.startNewConfigToJob(), child: Text("Run") ), ] ) ]) ); } }
- 方案3:添加永久标记避免控制器被回收
因为你没有使用GetX的路由体系,Get不会自动管理控制器的生命周期,可以在注入时添加permanent: true参数,避免控制器被意外回收:
Get.put(JobListController(), permanent: true); Get.put(NavigationBarController(), permanent: true);
内容的提问来源于stack exchange,提问作者Dmitry Bubnenkov
相关产品推荐
相关产品推荐

