Todd Chambery
Todd Chambery

Reputation: 3455

How to automatically initialize parent field?

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) {

Upvotes: 5

Views: 1325

Answers (2)

mhKarami
mhKarami

Reputation: 1014

first add constructor for parent with this.propertyName then use super.parentPropertyName

abstract class Failure {
  int? code;
  String? message;
  Failure({this.code,this.message});
}

class ServerFailure extends Failure {
  ServerFailure({super.code, super.message});
}

Upvotes: 0

Matt B
Matt B

Reputation: 6312

While your case is common, at this time the dart language spec specifically says:

Executing an initializing formal this.id causes the field id of the immediately surrounding class to be assigned the value of the corresponding actual parameter.

This essentially tells us that this.variable notation, 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:

class Type {
  String name;
}

class Language extends Type {
  String id;
  Language(name) {
    this.name = name;
  }
}

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:

class Type {
  String name;
  Type();
  Type.withName(this.name);
}

class Language extends Type {
  String id;
  Language(name) : super.withName(name);
}

This is assuming there's some reason that the default constructor for Type doesn't automatically initialize name so we created the 2nd named constructor instead.

Upvotes: 9

Related Questions