[英]Flutter and GetxController - How to manage state unreliability?
我目前在我的應用程序中遇到很多問題, get
package for Flutter ( https://pub.dev/packages/get ) 和以下 state 場景:
例如我有一個 GetxController UserController
。 我在不同的小部件中需要這個 controller,所以我在第一個小部件中使用Get.put()
初始化它,對於其他子小部件,我將使用Get.find()
調用它。 這樣可行。
但是:我有一些小部件有時會在 controller 初始化之前加載,有時會在初始化之后加載。 所以我收到很多"UsersController" not found
的錯誤。 也許這個問題存在一些解決方法?
您可以在應用程序啟動之前使用 Bindings class 初始化UsersController
class。
class UsersController extends GetxController {
static UsersController get i => Get.find();
int userId = 5;
}
class UsersBinding extends Bindings {
@override
void dependencies() {
Get.put<UsersController>(UsersController());
}
}
void main() async {
UsersBinding().dependencies();
runApp(MyApp());
}
通過這種方式,您的 UsersController 可以保證在加載任何 Widgets 之前在您的應用程序中的任何位置可用。
class MyHomePage extends StatelessWidget {
final UsersController uc = Get.find();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GetX Bindings'),
),
body: Center(
child: Obx(() => Text('userId: ${uc.userId}')),
),
);
}
}
嘗試添加
GetMaterialApp(
smartManagement: SmartManagement.keepFactory,
)
這樣它就可以存儲那些實例的工廠
或者確保添加permanent
Get.put<Repo>(Repo(), permanent: true);
這樣它就永遠不會從 memory 中刪除
如果您需要檢查 class 是否已初始化,您最多將 class 保留在 memory 中,並設置為permanent:true
並設置tag:'anything you want for check this object'
property in Get.put
function,現在您可以檢查
bool Get.isRegistered<className>(tag: 'TagInPut')
如果沒有特別的原因,你可以在main function 調用Get.put(UserController()) 並使用GetMaterialApp 包裝材料應用程序。
如果您使用get在您的應用程序中提供某些內容的實例,meaby https://pub.dev/packages/get_it可以幫助您更多。 只要確保你使用allowReassignment==true
這樣你就可以更新你的實例,如果你想保存一個全新的 controller,但如果你想使用相同的總是 get_it 是你的最佳選擇
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.