weenzeel
weenzeel

Reputation: 847

Constructor syntactic sugar for setting fields in Dart fails when fields are added via mixin

Why doesn't constructor syntactic sugar for setting fields work when importing fields from a mixin?

mixin Nameable { 

  var name = '';

}

class Person with Nameable {

  Person(this.name);

}

Fails with error-message 'name' isn't a field in the enclosing class.

This is ok though

mixin Nameable { 

  var name = '';

}

class Person with Nameable {

  Person(String name) {
    this.name = name;
  }

}

Report as a bug?

Upvotes: 0

Views: 486

Answers (1)

lrn
lrn

Reputation: 71903

Initializing formals, and initializer list entries, in generative constructors can only initialize fields which are declared in the same class.

A field introduced by a mixin, like here, is not declared in the class. It's mixed into a mixin application class, Object with Namable, which becomes the superclass of Person.

Assigning to the field in the body of a constructor is just normal assignment, not initialization. It wouldn't work if you wanted the field to be final.

Upvotes: 1

Related Questions