I have an Identity class in dart which looks (simplified) like this
class Identity {
final String phoneNumber;
Identity({@required this.phoneNumber});
Identity.fromJson(Map<String, dynamic> json)
: phoneNumber = json['phoneNumber'];
}
I will use this class to send an http POST to my identity service; this service will return a json which I want to map to ActiveIdentity, which looks like this (also simplified).
class ActiveIdentity extends Identity {
final String id;
ActiveIdentity.fromJson(Map<String, dynamic> json)
: id = json['id'];
}
Now, is there a way to extend or call fromJson in Identity so that I can "extend" this method? Ideally when calling fromJson in ActiveIdentity I should receive a new ActiveIdentity instance with all properties inititalized (phoneNumber and id) but on ActiveIdentity I only want to deal with id.
I also tried to think about this in terms of mixins, but failed miserably... any idea on how would be the best way to achieve this?
Thanks!
I think the following should solve your problem:
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');
}
}
Try having a look at the Dart documentation of constructors for clarification on this topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With