flutterdependency-injectioninjectable

Flutter injectable abstract class


I am trying to use injectable for my project but when i try this part of code:

@injectable
abstract class TodoRepository {
  Future<Either<Failure, DayTodosEntity>> getDayDodo(DateEntity date);
}  

after run build_runner this error occurs:

[TodoRepository] is abstract and can not be registered directly! 
if it has a factory or a create method annotate it with @factoryMethod

can't understand what am I missing.


Solution

  • @injectable decorator marks the class to be processed by the di (dependency injection) package.

    di is supposed to get you an instance of this class when you ask for it later on. but you also marked the class as "abstract" and abstract classes can not be instantiated.

    If you have single implementation for this abstraction, you only need to add the decorator for the implementation

    @Injectable(as: AbstractClass) 
    class ConcreteClass implements AbstractClass {}
    

    If you have multiple implementations you can achieve that by

    @Named("impl1")  
    @Injectable(as: AbstractClass)  
    class ConcreteClassImpl1 implements AbstractClass {}  
      
    @Named("impl2")  
    @Injectable(as: AbstractClass)  
    class ConcreteClassImpl2 implements AbstractClass {} 
    

    consuming the intended implementation

    @injectable  
    class Consumer {  
       final AbstractClass abstractClass;  
        Consumer(@Named('impl1') this. abstractClass)  
    }