ele*_*nad 3 flutter flutter-getx
目前,我的应用程序中的getFlutter 包 ( https://pub.dev/packages/get ) 和以下状态场景存在许多问题:
例如我有一个 GetxController UserController。我需要在不同的小部件中使用此控制器,因此我在第一个小部件中使用它进行初始化Get.put(),对于其他子小部件,我将使用Get.find(). 这样可行。
但是:我有一些小部件,有时在控制器初始化之前加载,有时在控制器初始化之后加载。所以我得到了很多"UsersController" not found错误。也许这个问题有一些解决方法?
UsersController您可以在应用程序启动之前使用 Bindings 类初始化您的类。
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());
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,在加载任何小部件之前,可以保证您的 UsersController 在应用程序中的任何位置都可用。
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}')),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15835 次 |
| 最近记录: |