ra9*_*a9r 14 abstract-class dart firebase flutter google-cloud-firestore
我正在尝试创建一个抽象类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,
};
}
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我没有收到任何错误,但是当我忽略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,
};
}
}
Run Code Online (Sandbox Code Playgroud)
我不能定义一个抽象的命名构造函数并且让它成为一个具体类中的 require 实现吗?如果没有,这样做的正确方法是什么?
小智 11
正如 Dart 语言的官方指南中所述,构造函数是\xe2\x80\x99t 继承的,因此您不能对子类强制使用工厂构造函数。为了确保实现,它应该是类接口的一部分,而构造函数不是。您可以查看这些相关的 stackoverflow 问题以获取更多信息:
\n\n\n| 归档时间: |
|
| 查看次数: |
4179 次 |
| 最近记录: |