Implementing SL pattern via get_it
The SL pattern involves delegating dependency creation to a central registry, known as the service locator. Any consumer can then retrieve any dependency they need from this central registry, without needing to know how it is created. The main difference from DI is that consumers are typically aware of the SL and are tightly coupled to it. We will provide a more detailed comparison and discuss when to choose each pattern at the end of this chapter. For now, let’s see how we can implement the SL pattern to gain a better understanding.
A popular library for implementing the SL pattern in Flutter is get_it
. To use it, we need to add it to our pubspec.yaml
file. Then, similar to RepositoryProvider
, we need to register our dependencies using the GetIt.instance
object. The syntax is similar to what we have seen with CartModel.instance
. GetIt
serves as a service registry where we register the dependencies we will need. This registry itself is a...