If you ever worked with Getx, you will see Get.put(), Get.lazyPut() and Get.putAsync(). Let’s see the difference between them.
Get.put()
Get.put() is used for inserting controller to memory and it’s get inserted immediately when your app boots. Because Getx will initialize the controller before you use them.
It’s not memory efficient.
class ControllerOne extends GetxController {
int a = 1;
@override
void onInit() {
print('ControllerOne onInit');
super.onInit();
}
@override
void onReady() {
print('ControllerOne onReady');
super.onReady();
}
}
final controller = Get.put(ControllerOne());
And see the output
ControllerOne onInit
ControllerOne onReady
Get.lazyPut()
Get.lazyPut() is also used for inserting the controller into memory. But it’s only called when you use them with a certain view or call them.
Once you call a controller or it’s instances, it will be loaded into memory immediately and ready to use then.
class ControllerTwo extends GetxController {
int b = 2;
@override
void onInit() {
print('ControllerTwo onInit');
super.onInit();
}
@override
void onReady() {
print('ControllerTwo onReady');
super.onReady();
}
}
final controller = Get.lazyPut(() => ControllerTwo());
See the output
/* nothing will be printed right now */
But if you try to use it, then will see that it’s get initialized.
ControllerTwo onInit
ControllerTwo onReady
Get.putAsync()
Get.putAsync() is loaded resources lazily and also wait. You need to inject controller using this if you load resources for external space like storage or database.
So if your controller return Future then you should use Get.putAsync() to inject resources.
Get.putAsync<CountController>(() async => await CountController());
Another example with SharedPreferences package.
class StorageService extends GetxService {
static StorageService get to => Get.find();
late final SharedPreferences _prefs;
Future<StorageService> init() async {
_prefs = await SharedPreferences.getInstance();
return this;
}
}
So here in the above code, GetxService which is also a controller has a method() init() and this method return Future object.
So if we inject this controller and get the instances of SharedPreferences, then we have to inject like below
await Get.putAsync<StorageService>(() => StorageService().init());
Summary
To my understanding put
already puts an instance of the class directly in memory while lazyPut
just puts a builder for it in it.
A benefit of lazyPut
is that it saves memory until you actually find
it. And you can also put more complex code in the builder for it. Another benefit of lazyPut
is that you can also say fenix: true
on it which means it’s able to be reconstructed in case it got disposed of before.
I would think the only benefit of using put
is that find
should be slightly faster then when called because it doesn’t need to call a builder first to get the instance. I don’t know if there are other benefits.
Getx complete app