Initializing final fields from a subclass in Dart
This does not work:
abstract class Par {
final int x;
}
class Sub extends Par {
Sub(theX) {
this.x = theX;
}
}
I am getting an error in Par indicating that x should be initialized:
warning: The final variable 'x' must be initialized
warning: 'x' cannot be used as a setter, it is final
+3
source to share
1 answer
Give the superclass a constructor and make the subclass call super
:
abstract class Par {
final int x;
Par (int this.x) {}
}
class Sub extends Par {
Sub(theX) : super(theX)
}
You can make the constructor the same as because the methods and fields that start with _
are private in Dart :
abstract class Par {
final int x;
Par._(int this.x) {}
}
class Sub extends Par {
Sub(theX) : super._(theX)
}
+2
source to share