Search⌘ K
AI Features

The Get.lazyPut Method

Explore how to implement lazy dependency injection using Get.lazyPut in Flutter's GetX framework. This lesson guides you through conditional initialization, managing multiple shared instances, and optimizing memory use with features like the fenix parameter. You will learn to control dependency lifecycle efficiently and apply these concepts through a hands-on counter app demonstrating theme-based behavior changes using lazy-loaded controllers.

Lazy loading dependencies

Get.lazyPut enables us to lazily load the dependencies into the memory. By lazy load, we mean that even though the dependencies will be initialized instantly, they will be allocated space in memory only when Get.find is called for the first time. Unlike Get.put, it does not call Get.find internally.

So when would we want to load our dependencies lazily? One good use case is when we place our dependencies in intialBinding:

Dart
class HomeBinding implements Bindings {
@override
void dependencies() {
Get.lazyPut<Controller>(() => Controller()); // Dependency declared here.
}
}
GetMaterialApp(
initialBinding: HomeBinding(), // Dependency initialized here.
);
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(Get.find<Controller>().name); // Dependency loaded here.
}
}

The above code is a reflection of the high-quality dependency organization that GetX offers. Dependencies are declared in HomeBinding, initialized within GetMaterialApp, and loaded inside the HomePage widget. This way, we can place all our dependencies inside initialBinding without worrying about them taking memory as they are loaded only when used by a widget.

Conditionally initializing dependencies

As we can notice, the syntax of ...