我正在尝试创建一个抽象类Firestorable
,该类将确保子类覆盖已命名的构造函数fromMap(Map<String, dynamic> map)
代码看起来像这样...
abstract class Firestorable {
/// Concrete implementations will convert their state into a
/// Firestore safe [Map<String, dynamic>] representation.
Map<String, dynamic> toMap();
/// Concrete implementations will initialize its state
/// from a [Map] provided by Firestore.
Firestorable.fromMap(Map<String, dynamic> map);
}
class WeaponRange implements Firestorable {
int effectiveRange;
int maximumRange;
WeaponRange({this.effectiveRange, this.maximumRange});
@override
WeaponRange.fromMap(Map<String, dynamic> map) {
effectiveRange = map['effectiveRange'] ?? 5;
maximumRange = map['maximumRange'] ?? effectiveRange;
}
@override
Map<String, int> toMap() {
return {
'effectiveRange': effectiveRange,
'maximumRange': maximumRange ?? effectiveRange,
};
}
}
执行此操作时不会出现任何错误,但是当我省去fromMap(..)
构造函数的具体实现时,也不会出现编译错误。
例如,以下代码将编译而没有任何错误:
abstract class Firestorable {
/// Concrete implementations will conver thier state into a
/// Firestore safe [Map<String, dynamic>] representation.
Map<String, dynamic> convertToMap();
/// Concrete implementations will initialize its state
/// from a [Map] provided by Firestore.
Firestorable.fromMap(Map<String, dynamic> map);
}
class WeaponRange implements Firestorable {
int effectiveRange;
int maximumRange;
WeaponRange({this.effectiveRange, this.maximumRange});
// @override
// WeaponRange.fromMap(Map<String, dynamic> map) {
// effectiveRange = map['effectiveRange'] ?? 5;
// maximumRange = map['maximumRange'] ?? effectiveRange;
// }
@override
Map<String, int> convertToMap() {
return {
'effectiveRange': effectiveRange,
'maximumRange': maximumRange ?? effectiveRange,
};
}
}
我无法定义一个名为构造函数的抽象,是否将其作为具体类中的require实现?如果没有,那么正确的方法是什么?
答案 0 :(得分:0)
如Dart语言constructors aren’t inherited的官方指南中所述,因此您不能对子类强制执行工厂构造函数。为了确保实现,它应该是构造函数不属于的类接口的一部分。您可以查看以下相关的stackoverflow问题以获取更多信息: