flutter 您需要调用“Get.put(dynamic())”或“Get.lazyPut(()=>dynamic())”

eqoofvh9  于 2022-11-25  发布在  Flutter
关注(0)|答案(2)|浏览(656)

我收到错误未处理的异常:找不到“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(),
  ),
  );
 }
xqnpmsa8

xqnpmsa81#

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指定,但不设置它们也可以。

fdbelqdn

fdbelqdn2#

您正在Get.put之前呼叫Get.find。
Get.put示例化示例,而Get.find试图找到它,因此确保在使用Get.find之前创建示例。

相关问题