Is it possible to automatically initialize fields from a parent class in the constructor?
I get the syntax error:
Could not match parameter initializer ‘this.name’ with any field
class Type {
String name;
}
class Language extends Type {
String id;
Language(this.name) {
While your case is common, at this time the dart language spec specifically says:
This essentially tells us that
this.variablenotation, in the constructor arguments, will only work on variables in the immediate class and not any parent classes. There are a couple of solutions available: The first is to assign it within the constructor’s body:Alternatively, if we can change the parent class to have a constructor which will initialize the variable then we can use the initializer list in the child class:
This is assuming there’s some reason that the default constructor for
Typedoesn’t automatically initializenameso we created the 2nd named constructor instead.