GetX Singletons | Made Flutter Easy

Created At: 2023-09-14 18:07:00 Updated At: 2023-10-01 08:39:34

This is another reason why Flutter GetX better than BLoC or Riverpod. What is it? It's the Singleton nature of the classes that you create with GetxController or GetxService. If your class extends GetxController or GetxService, then you can easily have a Singleton class with a minor tweak or change during depedency injection.

GetxController

We will take a look at it from GetxController. GetxController is the most simple one, that we extend in our class. It is also by nature implement Singleton. And what do I mean by this? 

Your controller becomes a dependency for Widgets. They depend on controllers. Controller are injected as dependency using

Get.put(YourController())

In your UI or using Global injection method.

GetxController comes with life cycle methods like onInit(), onReady() and onClose(). Which means your injected controller would be destroyed when they are not needed.

By default every previous screen is destroyed when you go to a new screen or route. This is to save the memory and the screen and controller gets reinitialized when you go back to the previous one. But this is still Singleton. why? Because if you try to get the controller instance you will get the same one. 

In general we get the controller instance using Get.find<YourController>. You may try to find it twice or look for the instance twice and you will check the instance's hashCode, you will see that they are same. Hence they are Singleton in nature. 

And now if we want our classes to live through out the app lifecye, we need to use another parameter. See the line below.

Now we can prevent this behavior(get destroyed) with with permanent:true

final controller = Get.put(YourController(), permanent:true);

With above way of dependency injection your controller will stay in the memory. But you need to be carefull whether you want to keep in the memory or not.

GetxService

If GetxService is extended by your class, then there would be only instance of this class and it won't be destroyed by GetX until you kill your app. 

It will stay alive. So in nature it acheives true Singleton nature, since it will have only one instance and you can not recreate a second one.

 

Comment

Add Reviews