Patterns, Data, and Input

Inversion of Control and Dependency Injection


Learning Objectives

  • You know of inversion of control and dependency injection.

In the previous chapter, we created an application that separated the view from the controller. The view was implemented as a stateless widget, and the controller was implemented as a separate class. However, the view used the controller directly, creating an instance of it in the view class.

class CountController {
  // code
}

class ClickCounterView extends StatelessWidget {
  final controller = CountController();

  // code
}

This means that the view is tightly coupled to the controller, which makes it difficult to test and use the view in isolation. This is where inversion of control and dependency injection come in.

Inversion of control is a technique where the task of creating and managing objects is delegated to a framework. This allows the framework to manage the flow of the application, rather than having the developer create and manage objects directly. Dependency injection on the other hand, is a technique where dependencies are provided to a class from the outside by the framework.

Using inversion of control and dependency injection makes the application more modular and easier to test, as the dependencies could be replaced with mock objects or other implementations, and the classes could in principle be also used in isolation.

GetX supports inversion of control and dependency injection through the Get.lazyPut method, which registers a dependency in the application, making it available for use from other parts of the application. The Get.find method then can be used to retrieve the dependency from the application, allowing it to be used in the class that needs it.

Loading Exercise...

The Get.lazyPut is given a type and a function. The type is the type of the dependency, and the function is a function that creates the dependency. The method is called at the beginning of the application, typically in the main function, when the dependencies are registered to the application.

The Get.find on the other hand is given the type of the dependency, and it returns the dependency if it has been registered in the application.

Concretely, when using inversion of control and dependency injection with GetX, an application would look as follows.

Run the program to see the output
Loading Exercise...