我在 dart 中有一个 Identity 类,它看起来(简化)如下
class Identity {
final String phoneNumber;
Identity({@required this.phoneNumber});
Identity.fromJson(Map<String, dynamic> json)
: phoneNumber = json['phoneNumber'];
}
我将使用这个类向我的身份服务发送一个 http POST;此服务将返回一个我想映射到 ActiveIdentity 的 json,它看起来像这样(也简化了)。
class ActiveIdentity extends Identity {
final String id;
ActiveIdentity.fromJson(Map<String, dynamic> json)
: id = json['id'];
}
现在,有没有办法在 Identity 中扩展或调用 fromJson 以便我可以“扩展”这个方法?理想情况下,在 ActiveIdentity 中调用 fromJson 时,我应该收到一个新的 ActiveIdentity 实例,其中所有属性都已初始化(phoneNumber 和 id),但在 ActiveIdentity 上,我只想处理 id。
我也试图从 mixin 的角度考虑这个问题,但失败了……关于如何实现这一目标的最佳方法有任何想法吗?
谢谢!
最佳答案
我认为以下应该可以解决您的问题:
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');
}
}
试试看一下 Dart documentation of constructors为了澄清这个话题。
关于dart - 在 dart 中使用 fromJson 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52676889/