【问题标题】:Flutter injectable abstract classFlutter 可注入抽象类
【发布时间】:2021-10-05 11:15:50
【问题描述】:

我正在尝试为我的项目使用可注入但当我尝试这部分代码时:

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

run build_runner之后出现这个错误:

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

无法理解我错过了什么。

【问题讨论】:

    标签: flutter dependency-injection injectable


    【解决方案1】:

    @injectable 装饰器标记要由 di(依赖注入)包处理的类。

    di 应该会在您稍后请求时为您提供此类的实例。但是您也将该类标记为“抽象”,并且无法实例化抽象类。

    如果你有这个抽象的单一实现,你只需要为实现添加装饰器

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

    如果你有多个实现,你可以通过

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

    使用预期的实现

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

    【讨论】:

    • 我也有这个类的实现。你能给我一个如何将它们绑定在一起的例子吗?
    • 当然,如果你有这个抽象的单一实现:你只需要为实现添加装饰器``` @Injectable(as: AbstractClass) class ConcreteClass implements AbstractClass {} ```
    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多