0 purchases
dependency injection flutter
Dependency Injection for Flutter #
Flutter Brazil
Injecting #
To inject a singleton:
The Singleton instance will be unique. And every time you try to fetch,
Injector will return the very same instance.
Injector.instance.inject<MyInstanceType>(()=>MyInstance());
copied to clipboard
By default, all injections made by the inject method will have
the type of a Singleton, but you can change it with tye type arg.
Injecting a lazy singleton
A lazy singleton will only be instantiated once will call it from Injector.
It helps a lot in saving RAM.
Injector.instance.inject<MyInstanceType>(()=>MyInstance(), type: InjectionType.lazySingleton);
copied to clipboard
To inject a factory:
A factory is the instance type that will return always as a brand new instance.
It can be useful to get a service for example.
Injector.instance.inject<MyInstanceType>(()=>MyInstance(), type: InjectionType.factory);
copied to clipboard
and get all of them with:
var myInstance = Injector.instance.get<MyInstanceType>();
copied to clipboard
Get your controller in your widget
class MyView extends StatelessWidget with InjectionMixin<MyController> {
void doSomething() {
controller.onDoSomething();
}
@override
Widget build(BuildContext context) {
return Container();
}
}
copied to clipboard
Testing with Injector
One of the great qualities of Injector is to provide an easy way to
test your code in unit tests.
In your class test, at the setUpAll body, use:
Injector injector;
setUpAll(() {
injector = Injector.instance;
injector.inject<MyServiceInterface>(()=> MyMockedService());
});
test("Testing the get all", () {
// Since you injected the MyServiceInterface
// it will return a class of MyServiceInterface type,
// but with the MyMockedService implementation.
var myService = injector.get<MyServiceInterface>();
// just as you were going to do in your real MyServiceImpl
var result = myService.getAll();
})
copied to clipboard
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.