是否可以在Dart中定义一个名为构造函数的抽象?

时间:2019-05-23 04:22:22

标签: firebase dart flutter google-cloud-firestore abstract-class

我正在尝试创建一个抽象类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实现?如果没有,那么正确的方法是什么?

1 个答案:

答案 0 :(得分:0)

如Dart语言constructors aren’t inherited的官方指南中所述,因此您不能对子类强制执行工厂构造函数。为了确保实现,它应该是构造函数不属于的类接口的一部分。您可以查看以下相关的stackoverflow问题以获取更多信息:

How to declare factory constructor in abstract classes

How do i guarentee a certain named constructor in dart

相关问题