具有命名构造函数的泛型类型的 Dart 抽象类

Baj*_*Bob 8 dart

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

Dart 编译器抛出异常T.fromJson -> Invalid constructor name.

我尝试对此进行编码:

abstract class JsonMap<T> {
  Map toJson();
  T.fromJson(Map m);
}
Run Code Online (Sandbox Code Playgroud)

Dur*_*rdu 5

我在同一个概念上苦苦挣扎(在同一个地方......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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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