Proper way to persist / store data in GetXController in flutter

Issue

I have this class and use "reactive" state management e.g.

"".obs

Now I plan to initialize my state from local storage (get_storage) onInit()

problem:

where do I persist my data? As soon as some state changes, I want to persist it as well.

I tried using a listener but it never fires.

Currently I have this:

class CosController extends GetxController {
  final box = GetStorage();

  RxString econtactnr = ''.obs;

  @override
  void onInit() {
    super.onInit();
    addListener(() { //NEVER fires
      print('hellowwww listener');
    });
    econtactnr.value = box.read('econtactnr') ?? '';
}

What is a best practice to store state to disk in GetXControllers using reactive state management?

EDIT: I noticed that you can do:

    econtactnr.listen((x) {
      box.write('econtactnr', econtactnr.value);
    });

question: is that ok? do I have to cancel that subscription as well?

Solution

GetX provides Workers for this type of functionality. The ever method can listen and store the updated value whenever it changes.

Try this in your onInit

  @override
  void onInit() {
    super.onInit();
    econtactnr.value = box.read('econtactnr') ?? '';
    ever(
      econtactnr,
      (value) {
        box.write('econtactnr', value);
      },
    );
  }

This will work and persist as long as you have await GetStorage.init(); happening before you initialize with Get.put(CosController());

If you need that to be stored throughout the entire lifecycle of your app, then you don’t need worry about disposing it because you always want it listening.

If you do want to dispose it for whatever reason, you could save the listener into a Worker variable.

 Worker worker;

  @override
  void onInit() {
    super.onInit();
    econtactnr.value = box.read('econtactnr') ?? '';
    worker = ever(
      econtactnr,
      (value) {
        box.write('econtactnr', value);
        debugPrint(value);
      },
    );
  }

Then dispose by using worker.dispose();

Answered By – Loren.A

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.