Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 486
reza Avatar asked Mar 15 '26 22:03

reza


1 Answers

@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)  
}
like image 56
Salah Avatar answered Mar 18 '26 21:03

Salah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!