Home > database >  How to put Flutter GetXController permanently in memory?
How to put Flutter GetXController permanently in memory?

Time:11-14

I am using get package.

Here's what my code looks like,

class MyController extends GetXController{
//code to fetch data from firebase
}

class SecondScreen extends GetView<MyController>{
  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: MyController(),
      builder: (controller) {
        return Scaffold(
        //code...
        );
      },
    );
}
}

Doubt: I have a button, using which I am navigating to the secondScreen from homePage, and everytime I tap on the button the controller MyController is initialized again and so the data is fetched again. But I want to do something that will keep that controller that is initizlized the first time in memory permanently. How can I do that?

I know that, we can do something like this, Get.put(Controller(), permanent: true); But, in my code, I haven't used Get.put method anywhere as when the class extending GetView is called the controller is initialized automatically.

CodePudding user response:

Well, actually you are putting/initializing MyController. Just not inside the GetX dependency container. Because you are doing:

GetBuilder(
 init: MyController(),
 .... 
)

What you should do instead is:

GetBuilders(
 init: Get.put(MyController()),
 .... 
)

That way you are letting GetX dependency manager to manage your dependencies. And it's smart enough to know that that route is on the backstack so doesn't remove from memory.

  • Related