Flutter Dependency Injection

Ivan Terekhin
2 min readDec 24, 2019

--

Dependency Injection ( https://en.wikipedia.org/wiki/Dependency_injection) (DI) is a very common technique that is used in Software Development. Briefly, it allows you to depend on the interface rather than on implementation and easily switch implementation. For example, you have some kind of StorageService class that provides methods for data persisting. And you are using SharedPrefs to persist data. And then you decided to switch to the Hive ( https://pub.dev/packages/hive). If your app is designed with DI in mind you will just implement the interface of StorageService and then provide it in your Injector or Locator.

Strictly speaking, all of the DI libs are Service Locators, because the “true” DI is not possible as I understand (no reflection) (so, it is like Koin, not like Dagger (if you are from Android world))

Of course, you are not required to use any libs to achieve that and you can do needed things manually. But, you can use the Provider ( https://pub.dev/packages/provider) or GetIt( https://pub.dev/packages/get_it) libraries.

I am using Provider in my apps. It is very straightforward. So, for example, we have the following StorageService interface:

Storage service example

And this basic Hive implementation:

We can set up the DI with Provider like this (please read the Provider documentation to understand where to put this):

Provider<StorageService>(
create: (_) => StorageServiceImpl(),
dispose: (context, StorageService service) => service.stop(),
),

Now you can access this StorageService anywhere you can call Provider.of<StorageService>(context) . Or you can propagate those services to MobX Stores or any utility classes.

--

--

Ivan Terekhin
Ivan Terekhin

Written by Ivan Terekhin

Mobile developer (Android, iOS, Flutter), AI and GameDev enthusiast. https://www.indiehackers.com/jeuler

No responses yet