具有空安全性的 flutter 继承

flutter inheritance with null safety

我正在将我的 flutter 项目升级到 null 安全支持。在这个项目中,我有抽象模型 classes 和继承。他们看起来像这样:

abstract class Technology {
  Guid id;
  String name;
  String description;
  String assetName;

  Technology();

  factory Technology.fromJson(Map<String, dynamic> json) =>
      TechnologyConverter().fromJson(json);

  Map<String, dynamic> toJson() => TechnologyConverter().toJson(this);
}
abstract class Research extends Technology {
  ResearchType researchType;

  Research();

  factory Research.fromJson(Map<String, dynamic> json) =>
      ResearchConverter().fromJson(json);
}
class LevelableResearch extends Research {
  LevelableResearch();

  factory LevelableResearch.fromJson(Map<String, dynamic> json) =>
      _$LevelableResearchFromJson(json);
  Map<String, dynamic> toJson() => _$LevelableResearchToJson(this);
}

build_runner 生成 json 序列化程序没有问题。 现在,当我更新到 null safety 时,我收到很多错误,从 "Non-nullable instance field 'id' must be initialized 开始。尝试添加一个初始化表达式,或在此添加一个字段初始化器构造函数,或者标记为 'late'"

如果我在构造函数中初始化字段,我必须调用 ": super()" 并使用继承的 class 中的所有需要​​的字段,结果写得太多了。 正如错误所说,我可以用 late 标记它,但我不确定这是否应该这样做。

编写这些 classes 的正确方法是什么,以便 build_runner 可以生成正确的 json 序列化程序?

If I initialize the field within the constructor, I have to call ": super()" with all the needed fields from the inherited class, which results in way too much writing.

仅当您修改构造函数以采用所需参数时,情况才会如此。必需的参数自然会阻止派生 class 的构造函数隐式调用 super() 来构造基础 class.

一般来说(即,不是专门针对您正在使用的 JSON 反序列化库),如果您不想为基础 class 构造函数提供必需的参数,那么您可以:

  • 通过构造函数的 .

    将成员初始化为非空默认值
  • 标记成员late。如果您可以保证访问成员之前对其进行初始化,则仅执行此操作。

  • 使成员可为空。如果您随后在无条件访问成员的任何地方添加空断言 (!),这等同于您的代码在空安全之前所做的。 (或者添加正常失败的空检查。)