Olha Bahlykh
Olha Bahlykh

Reputation: 11

Does GetX dispose of controller data when navigating to a different screen with another controller?

I am using multiple GetX controllers in my Flutter app, and I’ve noticed that when I navigate to a different screen that uses a different GetxController, the data in the previous controller seems to be lost or reset when I return.

For example:

Screen A → Uses ControllerA to fetch and display data. Navigate to Screen B → Uses ControllerB. Return to Screen A → ControllerA's data is gone (seems like it was disposed). My questions:

Here’s how I am initializing controllers:

class ControllerA extends GetxController {
  var data = [].obs;

  @override
  void onInit() {
    super.onInit();
    fetchData();
  }

  void fetchData() {
    // API call to fetch data
  }
}

And in main.dart:

void main() {
  Get.put(ControllerA()); // Or should I use Get.lazyPut()?
  runApp(MyApp());
}

What’s the best approach to keep controller data persistent across screens without it being reset or disposed?

Upvotes: 1

Views: 37

Answers (2)

Lightn1ng
Lightn1ng

Reputation: 430

for me im using GetBuilder data will persist if page still in the widget tree

GetBuilder<PageController>(
      global: false,
      init: PageController(),
      builder: (controller) => Scaffold(),
);

and route to page by .

Get.to(
      () => Page(),
    );

or you can do dependencies injection using binding method too

Upvotes: 1

Shailendra Rajput
Shailendra Rajput

Reputation: 2982

Does GetX automatically dispose of a controller when another screen with a different controller is pushed? GetX only disposes of a controller when it was instantiated using GetBuilder, Get.lazyPut(), or Get.put() with fenix: false, and it's no longer being used in the widget tree.

How can I persist data in a controller even when navigating to another screen? To keep a controller alive across screens, you can use either:

Get.put(ControllerA(), permanent: true): This keeps the controller alive throughout the app lifecycle.

Get.lazyPut(() => ControllerA(), fenix: true): This recreates the controller if it gets disposed but retains its state.

If you don't want the controller to be disposed at all, permanent: true is a good choice.

Should I use Get.put() or Get.lazyPut() to keep controllers alive across screens? Use Get.put(ControllerA()) if you always need it in memory (like global state or frequently used controllers).

Use Get.lazyPut(() => ControllerA(), fenix: true) if you want it to be recreated when needed (useful for large apps where you don't want unnecessary memory usage).

Would using Get.find() on return reinitialize it with fresh data? Get.find() will return the same instance without resetting data. if its not disposed.

Upvotes: 2

Related Questions