从 Dart 中的子类初始化最终字段

Initializing final fields from a subclass in Dart

这不起作用:

abstract class Par {
  final int x;
}

class Sub extends Par {
  Sub(theX) {
    this.x = theX;
  }
}

我在 Par 中收到一条错误消息,提示 x 必须初始化:

warning: The final variable 'x' must be initialized
warning: 'x' cannot be used as a setter, it is final

给超类一个构造函数,让子类调用super:

abstract class Par {
  final int x;
  Par (int this.x) {}
}

class Sub extends Par {
  Sub(theX) : super(theX)
}

您可以像这样将构造函数设为私有,因为 methods and fields starting with _ are private in Dart:

abstract class Par {
  final int x;
  Par._(int this.x) {}
}

class Sub extends Par {
  Sub(theX) : super._(theX)
}