I am new to Getx
's dependency injection, so can some one explain to me the benefits of Get.put()
and Get.lazyPut()
and tell me also what difference they have?
Short answer
Get.put()
will put ImmediatelyGet.lazyPut()
will put When you need it
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.
Get.put() :
Will inject a dependency and start executing immediately when it's injected, and I mean with that that its lifecycle methods like onInit()
and onReady()
will execute when you inject it like this:
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()); // will inject that dependecy, and immediately will call onInit() method then onReady() method
Debug log:
ControllerOne onInit
ControllerOne onReady
Get.lazyPut() :
will also inject a dependency, but it will not start executing the lifecycle methods onInit()
and onReady()
until you will really use that controller:
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()); // will inject that dependecy, and wait until it's used then it will call onInit() method, then onReady() method
Debug log:
/* nothing will be printed right now */
but if we do use the controller, as an example:
controller.b = 10;
then the controller will start running will start:
Debug log:
ControllerTwo onInit
ControllerTwo onReady
Hope this clarifies it!
In the case of lazyPut
, it only creates the instance, and it'll be instantiated only when is used, check more details here
© 2022 - 2024 — McMap. All rights reserved.