【发布时间】:2019-10-09 14:29:36
【问题描述】:
我正在尝试创建一个抽象类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,
};
}
}
我不能定义一个抽象的命名构造函数并让它成为具体类中的必需实现吗?如果不是,那么正确的方法是什么?
【问题讨论】:
-
我也在致力于“Firestorable”实现,以更轻松地访问 Firebase。与您类似,我想强制程序员实现 toMap 和 fromMap 方法。你介意分享一下你是如何实现的吗?有解决办法吗?我尝试与抽象静态方法进行交互,但是 dart 也不支持此方法,因此,我悬而未决。让我知道:)
-
@Jens 我最终走向了不同的方向,并使用 dart 注释创建了一个生成器。它没有相同的强制执行,但为我提供了一个更完整的解决方案,它根据类中的属性/注释为我生成序列化方法。
-
啊,我明白了——好主意。从长远来看,我还想实现一个插件,使我能够为模型和实体类生成代码。将牢记注释!
标签: firebase dart flutter google-cloud-firestore abstract-class