Search code examples
jsonflutterdartinheritanceextends

Flutter: inheritance, what i need know and how, an implemented method in parent that i need to use it in child and add more implementation on it


  • This is the parent which has an implemented method
abstract class CommonModel {
  int id;
  String name;
....
  Map<String, dynamic> toJson(){
     final Map<String, dynamic> data = new Map<String, dynamic>();
    data['Id'] = this.id;
    data['Name'] = this.name;
    return data;
  }
}
  • and this the the child class which i need to use the method [toJson] on it with its implementation and add more data.

import 'package:Elnota/models/governorate.dart';
import  'package:Elnota/models/abstract_common_model.dart';

class Centeral extends CommonModel{
 
  Governorate gov;

  Centeral({
    int id, 
    String name, 
    this.gov}) : super(id:id, name:name);

  Centeral.fromJson(Map<String, dynamic> json) :super.fromJson(json){
    gov = json['Gov'] != null ? new Governorate.fromJson(json['Gov']) : null;
  }


  Map<String, dynamic> toJson() {
   final Map<String, dynamic> data = new Map<String, dynamic>();
    data['Gov'] = this.gov;
  }

  
}

Solution

  • It's a little hard to understand what you need, but how about this:

    @override
    Map<String, dynamic> toJson() {
     final data = super.toJson();
     data['Gov'] = gov.toJson();
     return data;
    }