Flutter | Advanced Dependency Injection (Best Practice)

Bedirhan Saglam
3 min readOct 24, 2022

--

Suppose many Providers, BLoC etc. you have structure. You don’t want to manually inject them into the project one by one in main.dart. You can define them in a different file instead. Let’s examine it.

Let’s say you have created a BLoC structure. You know that before using this BLoC structure, you must define it with the BlocProvider structure. What if my Bloc definitions are too many? Or you are using Provider package. You wrote a separate Provider file for BottomNavigationBar and a separate Provider file for Tabbar. So how can you do this so that it is called best practice when injecting an application?

First we created a class. And we derive an _instance object from this class. Then we will call this object with the help of get method. The _init() method here will contain our BLoC and Provider structures. We’ll see soon.

Then I need to make some definitions. Because I am using services in my BLoC build. I’ve defined them here so that I can use them in the _init method and beyond.

By typing “late final” I promised to initialize these variables. And now I can define them in the _init method.

Next is to define the BLoC and Provider structures. We can keep this data in a List. Like this;

Let’s also define the Providers;

Now everything is ready! Now we have to define them in runApp. We will do this thanks to the instance we created at the beginning.

That’s it. We can do this by defining dozens of BLoC and Provider structures in the DependencyInjector class and writing just a few lines in the runApp. So what does this get you?
Time, code readability, gathering all your BLoC and Provider structures under one roof, etc.

Photo by Brett Jordan on Unsplash

The article ends here. Thank you for reading, see you in the next article bye bye. You can find me on Linkedin and GitHub:

Linkedin: https://www.linkedin.com/in/bedirhanssaglam/
GitHub: https://github.com/bedirhanssaglam

--

--