1

Flutter: The instance member'stars' can't be accessed in an initializer. Error

I asked the above question and received the following answer as the reason for the error.

reason : in dart you can't create a class level variable depends with another variable

↑ Is there any explanation in the official Dart, Flutter document (or something similar)?

Or is it derived from the Dart constructor mechanism?

If so, I would like to understand how the constructor works, which is the reason for this error.

Is there any relevant part in the official Dart, Flutter documentation, etc.?

森口万太郎
  • 805
  • 6
  • 20

1 Answers1

0

It is in fact due to Dart's constructor mechanism, specifically the order of execution during construction, as well as how Dart references instance variables within an object.

From the Instance Variables section of the Dart Language Tour:

If you initialize an instance variable where it is declared (instead of in a constructor or method), the value is set when the instance is created, which is before the constructor and its initializer list execute.

When you reference an instance variable in a Dart class via variableName there is an implied this reference to the instantiated object containing the variable. Due to the order of execution of Dart's object construction, this cannot reference the object during instance variable declaration because the object has not been created yet. Therefore, this.variableName and thus variableName (with implied this) cannot actually reference the instance variable.

Lee3
  • 2,882
  • 1
  • 11
  • 19