你需要调用 "Get.put(dynamic())" 或者 "Get.lazyPut(()=>dynamic())"。

4
我遇到了一个错误:未处理的异常:“dynamic”未找到。当我调用authController时,你需要调用“Get.put(dynamic())”或“Get.lazyPut(() => dynamic())”。以下是我的代码。
if (Get.find<AuthController>().isLoggedIn()) {
    //statements
  }

我的初始化函数
Future init() async {
// Core
final sharedPreferences = await SharedPreferences.getInstance();
  Get.lazyPut(() => sharedPreferences);

Get.lazyPut(() => ApiClient(
  appBaseUrl: AppConstants.BASE_URL,
));

// Repository
 Get.lazyPut(() => AuthRepo(apiClient:Get.find(), sharedPreferences: Get.find()));

 // controller
Get.lazyPut(() => AuthController(authRepo: Get.find()));

}

主方法

 void main() async{
  await di.init();
  runApp(
   child: MyApp(),
  ),
  );
 }
3个回答

4

Getx拥有一个很棒的功能,即Get.find(),可以找到你注入的依赖项,但就像你的例子中一样,你有多个依赖项,比如说sharedPreferencesAuthController,我们尝试找到它们,所以我们做了以下操作:

Get.find();
Get.find();

在上面的代码中,从逻辑上讲,它们是相同的,调用了相同的函数,但我们希望每个函数能找到特定的依赖项,那么 Getx 如何通过代码知道您想要什么呢?
这是通过对象类型实现的,您需要为每个依赖项指定一个通用的 Type,这样 Getx 就会使用该 Type 查找正确的依赖项,否则,它将只采用默认的类型,即 dynamic 类型,这就是引起 错误 的原因。
因此,在您的情况下,不要只输入:
Get.find(); // Getx: how I would know what should I return?
Get.find(); // Getx: how I would know what should I return?

您需要指定依赖的通用 Type:
Get.find<AuthController>(); // return AuthController dependency 
Get.find<SharedPreferences>(); // return SharedPreferences dependency

等等,你需要在所有这些地方指定通用的Type,以避免每次都出现此类异常。

注意:

只有Get.find()需要为其设置Type通用类型,Get.put()Get.lazyPut()也可以通过指定Type来设置,但不设置也可以。


1
你的清晰解释救了我的一天,我非常感谢你的帮助。 - Hanushka Suren

0

在调用 Get.put 前,您正在调用 Get.find。

Get.put 实例化该实例,而 Get.find 尝试查找它,因此请确保在使用 Get.find 之前创建该实例。


0

我在寻找X控制器时做错了什么:

这样是错误的:

_sizesTabXCtrl = Get.find()<LockerSizesWidgetXController>()

但是我需要找到这样的东西:
_sizesTabXCtrl = Get.find<LockerSizesWidgetXController>()

尝试一次这个,如果它解决了你的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接