Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend with fromJson in dart

Tags:

dart

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!

like image 675
David Avatar asked Oct 06 '18 07:10

David


1 Answers

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.

like image 128
alex kucksdorf Avatar answered Oct 08 '22 04:10

alex kucksdorf