我正處于使用物體和模型的情況。基本上我的物體描述了我的資料應該是什么樣子,我的模型擴展了這些物體并有一個函式 toMap 將它們轉換為 json 物件。
所以我有 2 個物體,Car 和 Brand,其中一個 Car 屬性是 Brand 型別。
class Car {
final String name;
final Brand brand;
const Car({
required this.name,
required this.brand,
});
}
class Brand {
final String label;
final String color;
const Brand({
required this.label,
required this.color,
});
}
然后我有 2 個模型 CarModel 和 BrandModel,它們分別擴展了 Car 和 Brand。
class CarModel extends Car {
CarModel({
required String name,
required BrandModel brand,
}) : super(
name: name,
brand: brand,
);
Map<String, dynamic> toMap() {
return {
'name': name,
'brand': brand,
};
}
}
class BrandModel extends Brand {
BrandModel({
required String label,
required String color,
}) : super(
label: label,
color: color,
);
Map<String, dynamic> toMap() {
return {
'label': label,
'color': color,
};
}
}
如您所見,在 中CarModel,我希望該brand屬性具有一個型別BrandModel。但是,它采用其超型別別。
所以最后,brand我的屬性CarModel有一個Brand.
我的問題是在 toMap 函式中,我想像這樣使用brand.toMap:
Map<String, dynamic> toMap() {
return {
'name': name,
'brand': brand.toMap(), // <= I want to use toMap() here, so I need brand to be of type BrandModel
};
}
有沒有辦法強制我的子類為從超類繼承的屬性使用不同的型別?
uj5u.com熱心網友回復:
有趣的問題。您正在嘗試實作繼承。因此,當您required BrandModel brand,在CarModel其擴展Car具有final Brand brand;欄位型別的建構式中提供時會發生什么。Brand從BrandModel物件中獲取必要的屬性/定義,這是您無法'brand': brand.toMap(),在Map<String, dynamic> toMap()方法內部呼叫的唯一原因,因為Brand類沒有此方法。
Child 具有 Parent 的所有屬性/功能/定義,但 Parent 不具有 child 的所有屬性。
解決方案
所以,你需要把toMap()在Brand類。這里抽象的用武之地。在這個階段,可能是toMap()方法不清楚你喜歡什么這會對身體內部,會是什么地圖?簡單地說,將其宣告為abstract. 另外,將類宣告為抽象類。抽象類應該有抽象方法。
現在,多型出現了。在BrandModel類內部,該toMap()方法將是一個覆寫方法。檢查以下測驗代碼(完整示例)。
class Car {
final String name;
final Brand brand;
const Car({
required this.name,
required this.brand,
});
}
abstract class Brand {
final String label;
final String color;
const Brand({
required this.label,
required this.color,
});
Map<String, dynamic> toMap();
}
class CarModel extends Car {
CarModel({
required String name,
required BrandModel brand,
}) : super(
name: name,
brand: brand,
);
Map<String, dynamic> toMap() {
return {
'name': name,
'brand': brand.toMap(),
};
}
}
class BrandModel extends Brand {
BrandModel({
required String label,
required String color,
}) : super(
label: label,
color: color,
);
@override
Map<String, dynamic> toMap() {
return {
'label': label,
'color': color,
};
}
}
void main() {
BrandModel brand = BrandModel(label:'Test',color : 'white');
CarModel car = CarModel(name: 'T',brand : brand);
print(car.toMap());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314631.html
