Flutter:继承,我需要知道什么以及如何实现,我需要在 child 中使用它并在其上添加更多实现的 parent 中的实现方法
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
- 这是parent,它有一个已实现的方法
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;
}
}
- 这是 child class,我需要在其实现中使用方法 [toJson] 并添加更多数据。
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;
}
}
有点难理解你需要什么,但是这个怎么样:
@override
Map<String, dynamic> toJson() {
final data = super.toJson();
data['Gov'] = gov.toJson();
return data;
}
- 这是parent,它有一个已实现的方法
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;
}
}
- 这是 child class,我需要在其实现中使用方法 [toJson] 并添加更多数据。
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;
}
}
有点难理解你需要什么,但是这个怎么样:
@override
Map<String, dynamic> toJson() {
final data = super.toJson();
data['Gov'] = gov.toJson();
return data;
}