Complete BLoC with Clean Architecture (group chat) Discount !! E-commerce App With Backend Source Code Video and Voice Chatting App Firebase Chatting App Source Code Complete Gym App BLoC State Management Source Code Complete Study App Buy Ticket Booking App Source Code Buy Travel App With Backend Source Code Complete Chat App Udemy Course Special Offer Discount !! Online Learning Course App (BLoC) Online Learning Course App (Riverpod) Online Learning Course App (Getx) Discount !! Shopping App (Provider) Cool Flutter Game Flutter Nodejs Chat App Flutter Nodejs Api And Firebase Chat App Riverpod Task Management App
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
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.
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
In your UI or using Global injection method.
GetxController comes with life cycle methods like
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
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.
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.