Flutter Dependency Injection

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 ():

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.



Mobile developer (Android, iOS, Flutter), AI and GameDev enthusiast. http://clover-republic.com/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store