I want to have a class that inherits some properties from another class in Dart. What's the best way to do it?
This is my parent class :
class Photo {
final String id;
final String owner, server, secret, title;
final int farm, isfamily, ispublic, isfriend;
final String url;
Photo(
{this.id,
this.owner,
this.secret,
this.server,
this.farm,
this.title,
this.ispublic,
this.isfriend,
this.isfamily,
this.url});
factory Photo.fromJson(Map<String, dynamic> parsedJson) {
return new Photo(
id: parsedJson['id'],
owner: parsedJson['owner'],
secret: parsedJson['secret'],
server: parsedJson['server'],
farm: parsedJson['farm'],
title: parsedJson['title'],
ispublic: parsedJson['ispublic'],
isfriend: parsedJson['isfriend'],
isfamily: parsedJson['isfamily'],
url: parsedJson['url_m']);
}
}
This is the child class that i want to create:
class gPhoto : Photo //inherits Photo
{
string ownername;
string dateadded;
gPhoto(
{this.ownername,
this.dateadded
});
factory gPhoto.fromJson(Map<String, dynamic> parsedJson) {
return new Photo(
ownername: parsedJson['ownername'],
dateadded: parsedJson['dateadded'']);
}
Will this work? the factory from the Photo class will work with my new class or do i have to create a separate class for gPhoto in order to map the json?
You need to check out dart syntax which is a bit different from languages like C# using :
for inheritance.
This is how you do it on your own:
class Photo {
final String id;
final String owner, server, secret, title;
final int farm, isfamily, ispublic, isfriend;
final String url;
Photo(
{this.id,
this.owner,
this.secret,
this.server,
this.farm,
this.title,
this.ispublic,
this.isfriend,
this.isfamily,
this.url});
factory Photo.fromJson(Map<String, dynamic> parsedJson) {
return new Photo(
id: parsedJson['id'],
owner: parsedJson['owner'],
secret: parsedJson['secret'],
server: parsedJson['server'],
farm: parsedJson['farm'],
title: parsedJson['title'],
ispublic: parsedJson['ispublic'],
isfriend: parsedJson['isfriend'],
isfamily: parsedJson['isfamily'],
url: parsedJson['url_m']);
}
}
class gPhoto extends Photo {
final String ownername;
final String dateadded;
gPhoto(
{id,
owner,
secret,
server,
farm,
title,
ispublic,
isfriend,
isfamily,
url,
this.ownername,
this.dateadded})
: super(
id: id,
owner: owner,
secret: secret,
server: server,
farm: farm,
title: title,
ispublic: ispublic,
isfamily: isfamily,
url: url);
factory gPhoto.fromJson(Map<String, dynamic> parsedJson) {
final photo = Photo.fromJson(parsedJson);
final ownername = parsedJson['ownername'];
final dateadded = parsedJson['dateadded'];
return gPhoto(
dateadded: dateadded,
ownername: ownername,
farm: photo.farm,
id: photo.id,
isfamily: photo.isfamily,
isfriend: photo.isfriend,
ispublic: photo.ispublic,
owner: photo.owner,
secret: photo.secret,
server: photo.server,
title: photo.title,
url: photo.url,
);
}
}
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