DartIn:A pragmatic lightweight dependency injection framework for Flutter developers

ditclear
2 min readMar 22, 2019

--

What is Flutter?

Flutter is Google’s mobile UI framework for crafting high-quality native interfaces on iOS and Android in record time. Flutter works with existing code, is used by developers and organizations around the world, and is free and open source.

I have been studying flutter for a few months , and have worked 3 years as an android developer。In the past years, I’d like to use DI (dependency injection) in my App , such as Dagger2 and Koin. But in Flutter, there don’t have DI tools, so I decide to develop a DI tool.

What is DartIn?

DartIn is a pragmatic lightweight dependency injection framework for Flutter developers. It is a light container inspired by flutter-provide and koin.

DartIn is pure Dart , and less than 300 lines in total.

you can set up by :

dependencies:
dartin: ^0.0.1

Key methods

  • single:Creates a provider with the value provided to it.
  • lazy:Creates a provider which will initialize using the [DartInFunction] the first time the value is requested.
  • factory:Creates a provider that provides a new value using the [DartInFunction] for each requestor of the value.
  • inject:get T from dartIns by T.runtimeType and params

more informations see dartin.dart.

Getting Started

  1. declare DartIn modules
//scope should always be initialized as a static const and passed around.
const test = DartInScope('test');
final viewModelModule = Module([
factory<HomeProvide>(({params}) => HomeProvide(params.get(0), get<GithubRepo>())),
])
..addOthers(test , [
///other scope
factory<HomeProvide>(({params}) => HomeProvide(params.get(0), get<GithubRepo>())),
]);
final repoModule = Module([
lazy<GithubRepo>(({params}) => GithubRepo(get<GithubService>())),
]);
final remoteModule = Module([
single<GithubService>(GithubService()),
]);
final appModule = [viewModelModule, repoModule, remoteModule];

2. Start dartIn

void main() {
startDartIn(appModule);
runApp(MyApp());
}

3. inject to your bloc or provide

//default
final service = inject<GithubService>();
//pass parameters
final test = inject<HomeProvide>(params: ['title']);
//different scope
final test = inject<HomeProvide>(scope:test, params: ['title']);

more examples see https://github.com/ditclear/mvvm_flutter.

DartIn is easy to use, and still improving.

🍺 welcome to fork and pull request.

--

--