Flutter: The power of DI and Injectable

Vovaklh
3 min readOct 4, 2022

--

Hi everyone! In this article I will tell what DI is and show my way of using it. Let’s go!

What is Dependency Injection

A few days ago I downloaded an app that shows the time I spend on my smartphone. Well, some days I spent more than five hours and it showed me a strong addiction. I have an iPhone 11.

It seems that I’m addicted to my iPhone. However, it is not. If I had any other smartphone, the results would not have changed. As a result, it turns out that I have a dependence on the abstraction — a smartphone, and my current one is its specific implementation. It’s time to get down to practice!

Practice

Imagine a situation where every first week you have to show the customer a UI with mock data, and at the end of the sprint, a completely finished logic. I hope you are familiar with the Repository pattern, which is responsible for receiving data, if not, I recommend you read it. The easiest way to solve the problem is to write methods in the repository that return mock data, and then add methods to receive real data (or replace them). However, doing it this way, we violate one of the principles of SOLID, called Single Responsibility. What is the solution? Create an abstract class of our repository and create two implementations, the first is responsible for mock data, and the other — for real data. In Bloc or in any other class that is responsible for State Management, you inject the abstraction, making it possible to replace the mock repository by a real repository.

Thus, you can inject the mock repository first, and later replace it with a repository that receives data from the API.

It is time to improve your hard skills

The letter O in SOLID stands for the open/closed principle. It declares that programming entities should be open for extension, but closed for modification.

When we replace one implementation with another, we violate this principle. And the developers of the Injectable package also thought about it, so we can create our dependencies under different environments. We will need to create a main file for each environment, describe them in launch.json and inject dependencies from each file with a specific environment. Or you can create one main file and use –dart-define to get the environment.

At the end we can do something like this.

Thank you for reading! I think native Android developers, who use Dagger for DI, can see similarities between Dagger and Injectable.

--

--