首页 > 解决方案 > 具有命名构造函数的通用类型的 Dart 抽象类

问题描述

我正在尝试在 Dart 中构造一个需要命名构造函数的抽象类。给定一些 Map (m),这个泛型类型必须能够实例化自己。

Dart 编译器正在抛出T.fromJson -> Invalid constructor name.

我尝试对此进行编码:

abstract class JsonMap<T> {
  Map toJson();
  T.fromJson(Map m);
}

标签: dart

解决方案


我在同一个概念上苦苦挣扎(在同一个地方...... API解析:))),但我没有找到合适的解决方案。

但也许你可以使用我在检查块模式时发现的东西(我没有将它用于我的模型部分):

abstract class SomeBase {
  void load();
}

class Provider<T extends SomeBase> extends InheritedWidget {
  final T something;

  Provider({
    Key key,
    @required this.something,
  }): super(key: key);

  @override
  bool updateShouldNotify(_) {
    return true;
  }

  static Type _typeOf<T>() => T;

  static T of<T extends SomeBase>(BuildContext context){
    final type = _typeOf<Provider<T>>();
    Provider<T> provider = context.inheritFromWidgetOfExactType(type);
    return provider.something;
  }
}

或者只使用它而不将其封装在继承的小部件中,并提供已经初始化的对象(如用户或您正在解析的任何内容),这些对象只是从提供的 JSON 加载值。


推荐阅读