1

As the Container widget has a constraints instance variable 。 But the constructor will also has a constraints parameter.

And in the initializor list, We can see code like this:

constraints = (****) constraints;

So how do we know which constraints is reference to the instance variable , and which one is reference to the function parameter? enter image description here

ximmyxiao
  • 2,622
  • 3
  • 20
  • 35

1 Answers1

3

The name collision is not a problem in constructor initializer lists. The left-hand-side of each initialization may only be a member variable. From the Dart language specification:

Initializer Lists

An initializer list begins with a colon, and consists of a comma-separated list of individual initializers.

[...]

An initializer of the form v = e is equivalent to an initializer of the form this.v = e, both forms are called instance variable initializers.

Meanwhile, the expression on the right-hand-side cannot access this and therefore can never refer to a member variable. Therefore:

class Foo {
  int x;

  Foo(int x) : x = x;
}

has no ambiguity: the member variable x is initialized from the x parameter.

The name collision can be a problem in a constructor body, however:

class Foo {
  int x;

  Foo(int x) : x = x {
    x *= 10; // This modifies the local `x` parameter.
  }
}

In such cases, the constructor body must be careful to explicitly use this.x if it needs to use the member variable, not the parameter of the same name.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • thanks, I got it ! one more question : where can I found the place for rule "The left-hand-side of each initialization may only be a member variable" like the link you post for the right-handside?Or It's some thing conventional? – ximmyxiao Jun 29 '21 at 10:52