parent class used for toJson method of extended child - or how to nest json with clean architecture pattern

Viewed 109

I am adapting my code to clean architecture (following the brilliant tutorial from Reso Coder) and have an issue now with the toJson method on a nested structure. The difference is that the data model class is extended from the data entity class, compared to my previous code.

I found the exactly same issue here, however, I wonder if there is a better/cleaner solution?!

class MyData extends Equatable{
  final List<MyNestedData> nested; 
  MyData(this.nested);
}

class MyNestedData extends Equatable {
  final int x;
  final int y;
  MyNestedData({this.x, this.y});
}
class MyDataModel extends MyData{
  final List<MyNestedData> nested; 
  MyDataModel(List<MyNestedDataModel> nested) : super (nested);
  
  Map<String, dynamic> toJson() => {
    "nested": List<dynamic>.from(nested.map((x) => x.toJson())),
  };
}

class MyNestedDataModel extends MyNestedData {
  MyNestedData({x, y}) : super (x: x, y: y);
  
  Map<String, dynamic> toJson() => {
    x: x,
    y: y
  }
}

MyDataModel obviously ignores the adapted parameter definition List<MyNestedDataModel> nested and uses List<MyNestedData> of the parent instead. So how would I then approach the toJson method within MyNestedDataModel instead?

0 Answers
Related