Reputation: 1502
I currently have many problems in my app with the get
package for Flutter (https://pub.dev/packages/get) and the following state scenario:
For example I have a GetxController UserController
. I need this controller in different Widgets, so I initialize it with Get.put()
in the first widget and for the other child widgets I'll call it with Get.find()
. That works.
But: I have some widgets that sometimes load before the controller got initialized and sometimes after. So I get many "UsersController" not found
errors. Maybe there exists some workaround for this problem?
Upvotes: 3
Views: 17241
Reputation: 675
if u need to check class is initialized, u most keep the class in memory with permanent:true
and set tag:'anything you want for check this object'
property in Get.put
function, and now u can check
bool Get.isRegistered<className>(tag: 'TagInPut')
Upvotes: 1
Reputation: 361
If there's no specific reason, you can just call Get.put(UserController()) at main function and wrap material app with GetMaterialApp.
Upvotes: 0
Reputation: 28050
You could initialize your UsersController
class using a Bindings class, prior to the start of your app.
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());
}
Done this way your UsersController is guaranteed to be available everywhere in your app, prior to any Widgets loading.
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}')),
),
);
}
}
Upvotes: 6
Reputation: 5182
try to add
GetMaterialApp(
smartManagement: SmartManagement.keepFactory,
)
so that it can store factory of those instanse
or make sure add permanent
Get.put<Repo>(Repo(), permanent: true);
so that it never get deleted from memory
Upvotes: 5
Reputation: 54
if you are using get to provide an instance of something across your app
meaby https://pub.dev/packages/get_it could help you more. just be sure that you use allowReassignment==true
so you can update your instance if you want save a full new controller, but if you want to use the same always get_it is perfect for you
Upvotes: -1