Flutter and GetxController - How to manage state unreliability?

Viewed 11891

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?

5 Answers

You could initialize your UsersController class using a Bindings class, prior to the start of your app.

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());
}

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}')),
      ),
    );
  }
}

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

if u need to check class is initialized, u most keep the class in memory with permanent:trueand 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')

If there's no specific reason, you can just call Get.put(UserController()) at main function and wrap material app with GetMaterialApp.

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

Related