在 dart 中使用 fromJson 扩展

Dav*_*vid 5 dart

我在 dart 中有一个 Identity 类,它看起来(简化)如下

class Identity {
  final String phoneNumber;

  Identity({@required this.phoneNumber});

  Identity.fromJson(Map<String, dynamic> json)
      : phoneNumber = json['phoneNumber'];

}
Run Code Online (Sandbox Code Playgroud)

我将使用这个类向我的身份服务发送一个 http POST;此服务将返回一个我想映射到 ActiveIdentity 的 json,它看起来像这样(也简化了)。

class ActiveIdentity extends Identity {
  final String id;

  ActiveIdentity.fromJson(Map<String, dynamic> json)
          : id = json['id'];
}
Run Code Online (Sandbox Code Playgroud)

现在,有没有办法在 Identity 中扩展或调用 fromJson 以便我可以“扩展”这个方法?理想情况下,在 ActiveIdentity 中调用 fromJson 时,我应该收到一个新的 ActiveIdentity 实例,其中所有属性都已初始化(phoneNumber 和 id),但在 ActiveIdentity 上,我只想处理 id。

我也试图从 mixin 的角度考虑这个问题,但失败了……关于如何实现这一目标的最佳方法有任何想法吗?

谢谢!

ale*_*orf 5

我认为以下应该可以解决您的问题:

class Identity {
  final String phoneNumber;

  Identity({@required this.phoneNumber});

  Identity.fromJson(Map<String, dynamic> json)
      : phoneNumber = json['phoneNumber'];
}

class ActiveIdentity extends Identity {
  final String id;

  ActiveIdentity.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        super.fromJson(json) {
    print('$phoneNumber $id');
  }
}
Run Code Online (Sandbox Code Playgroud)

尝试查看构造函数的 Dart文档以了解有关此主题的信息。