Dependency Injection for Flutter

Flutter Brazil

Pub style: effective dart GitHub stars

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

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);

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);

and get all of them with:

  var myInstance = Injector.instance.get<MyInstanceType>();

You may want to get them with args*:

  var myInstance = Injector.instance.get<MyInstanceType>(args: {
    'my_key': 1
  });
  //output: '1'
  print(myInstance.args['my_key'].toString());

*In order to do this, you have to implement this in your class:

class MyClass implements InjectionArgs {
  
  @override
  Map<String, dynamic> args = <String, dynamic> {};
  
}

and then you can use:


var myService = Injector.instance.get<MyService>(args: {
  'api_client': APIClient()
});

class MyService implements InjectionArgs {
  
  final _apiClientKey = 'api_client';
  
  @override
  Map<String, dynamic> args = <String, dynamic> {};
  
  Future<Response> getFoo() async {
    
    final client = args[_apiClientKey];
    return await client.get('api-my_foo_url.com/foo');
    
  }
  
}

Get your controller in your widget

  
    
class MyView extends StatelessWidget with InjectionMixin<MyController> {
  
  void doSomething() {
    controller.onDoSomething();
  }
  
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

    

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();
    
    
  })
  

Libraries

dependency_injection_flutter