2

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.

Mayur Agarwal
  • 1,448
  • 1
  • 14
  • 30
  • 1
    When ever you come to SecondScreen its build method called again and a new instance of MyController() is created. I suggest create MyController in HomeScreen and pass it through constructor to Second Screen. In MyController you can keep a flag to check data already fetched on not. – Sanjay Kumar Nov 12 '21 at 10:43
  • OK, so I put the controller permanently in the memory then, or it's unnecessary? – Mayur Agarwal Nov 12 '21 at 10:55
  • If you don't want to fetch data again you have to keep data in memory. If you want to save permanent even after app close you can use local database. – Sanjay Kumar Nov 12 '21 at 11:33

2 Answers2

5

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.

S. M. JAHANGIR
  • 4,324
  • 1
  • 10
  • 30
  • Now we can use Get.put(Controller(), permanent: true); also, right? – Mayur Agarwal Nov 14 '21 at 05:08
  • Yes! But when I was learning GetX i was having an issue just the exact opposite of yours. I mean it wasn't calling lifecycle methods. Therefore controllers shouldn't be permanent/fenix usually because they got they got lifecycles. – S. M. JAHANGIR Nov 14 '21 at 05:37
4

Adding "permanent" to where you use "get.put" will fix the problem

  • Get.put(Controller(), permanent: true);

my widgets were not staying permanently, this is how I solved it

SERCAN ARI
  • 41
  • 7