3

How can I use the setter of a private instance variable from the default constructor in Dart?

Given the example class:

class A {
  String name;
  int _age;

  int get age => _age;

  set age(age) {
    _age = age ?? 0;
  }

  A(this.name, this._age);
}

How can I use this constructor to go through the set age() function? Is there away aside from using a factory? I'd like to do something like this

A(this.name, newAge): age = newAge;

But I get an error forcing me to only set instance variables from the constructor, which has me just duplicating the setter:

A(this.name, newAge): _age = newAge ?? 0;

Am I missing something or is this just not possible with dart?

grizzasd
  • 363
  • 3
  • 15

1 Answers1

6

The initialization list of a constructor can be used only to initialize members (or call base class constructors). (Additionally, when the initialization list is executed, this isn't valid yet, so you can't access any members.)

If you want to do other kinds of initialization work, you can do it in the constructor body instead, at which point the object is considered to be sufficiently constructed for this to be valid:

A(this.name, int newAge) {
  age = newAge;
}

Also see:

jamesdlin
  • 81,374
  • 13
  • 159
  • 204