Using The Get - It Flutter Package: What Is Getit?

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Using the Get_It flutter package

This article will explain what get_it is, check different registration
methods, and give an example of how to use it in a Flutter application.

What is GetIt?
The get_it package is a service locator, in which you would have a
central registry where you can register the classes and then obtain an
instance of those classes. That can help us to obtain clean code and to
have a loosely coupled system.

Adding GetIt To Flutter


After creating a project, navigate to the pubspec.yaml file and add the
following:

Click CTRL + S to save, and you have successfully added get_it to your
Flutter application!
Example Using GetIt
So first to use it in your code you need to create an instance of GetIt
which can be done using two ways:

Now let’s assume we have the following class:

and we want to use it in a different class. Therefore we can register it


using get_it:
Then to access the Students class you can do:

This would print Ahmed in the terminal. Also, don’t forget to call
getItInit() inside the main() method:

In the above example we saw one registration type which is


registerFactory, but there are also other registration types:

registeryFactory: Will register a type so that a new instance will be


created on each call.

registerFactoryParam: It is the same as registerFactory, but the only


difference is that you can pass up to 2 parameters.
registerSingleton: Will register a type as Singleton, which means that
on each call the same instance will always be returned during the app
lifecycle.

registerLazySingleton: It is the same as registerSingleton, but the


only difference is that in this case the singleton is registered only when
it’s requested as a dependency for some other class.

For example with registerFactoryParam we can do the following:

and then to access the value of each field we can do:


Example with registerLazySingleton, we can do the following:

So let’s say we are using a layered architecture (presentation, domain,


data layer), and we don’t want the domain to know the implementation
details of the data layer then we can use an interface. Then using the
get_it package we can register the implementation class, but the
ServicesViewModel class will only depend on the abstraction.

For more details check: get_it

I hope you enjoyed reading this flutter tutorial, please feel free to leave any
comments or feedback on this post!

You might also like