目前我的应用程序存在很多问题get
Flutter 包(https://pub.dev/packages/get https://pub.dev/packages/get)以及以下状态场景:
例如我有一个 GetxControllerUserController
。我需要在不同的小部件中使用这个控制器,所以我用以下命令初始化它Get.put()
在第一个小部件和其他子小部件中,我将使用Get.find()
。这样可行。
但是:我有一些小部件,有时在控制器初始化之前加载,有时在初始化之后加载。所以我得到很多"UsersController" not found
错误。也许这个问题有一些解决方法?
你可以初始化你的UsersController
在应用程序启动之前,使用 Bindings 类。
Example
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 在应用程序中的任何位置都可用。
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}')),
),
);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)