chu*_*ubi 4 flutter flutter-getx
我收到错误未处理的异常:未找到“动态”。当我调用 authController 时,您需要调用“Get.put(dynamic())”或“Get.lazyPut(()=>dynamic())”,下面是我的代码。
if (Get.find<AuthController>().isLoggedIn()) {
//statements
}
Run Code Online (Sandbox Code Playgroud)
我的初始化函数
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()));
Run Code Online (Sandbox Code Playgroud)
}
主要方法
void main() async{
await di.init();
runApp(
child: MyApp(),
),
);
}
Run Code Online (Sandbox Code Playgroud)
Getx有一个很棒的功能Get.find(),它可以找到您注入的依赖项,但就像在您的示例中一样,您有多个依赖项,让我们sharedPreferences尝试AuthController找到它们,所以我们这样做了:
Get.find();
Get.find();
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,从逻辑上讲,它只是同一件事,调用相同的函数,但我们希望每个函数都能找到特定的依赖项,那么如何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?
Run Code Online (Sandbox Code Playgroud)
您需要指定依赖项 generic Type:
Get.find<AuthController>(); // return AuthController dependency
Get.find<SharedPreferences>(); // return SharedPreferences dependency
Run Code Online (Sandbox Code Playgroud)
等等,您需要Type在所有这些中指定泛型,以避免每次都出现这样的异常。
笔记:
只需要为它Get.find()设置一个泛型,并且可以由也指定,但不设置它们也可以。TypeGet.put()Get.lazyPut()Type