'Error: The instance member ... can't be accessed in an initializer
Why does this code:
class _SequentialTextPageState {
String jsonTextPref = 'seqtext';
int jsonTextSuff = 10;
String jsonText = jsonTextPref + jsonTextSuff.toString();
}
generate these errors?
Error: The instance member 'jsonTextPref' can't be accessed in an initializer.
Error: The instance member 'jsonTextSuff' can't be accessed in an initializer.
It seems to me that concatenation between String
and int
is correct?
Solution 1:[1]
You can only use constant expressions as initializers. x=this.y
is not constant.
Solution 2:[2]
Dart does not allow field initializers to refer to the object itself. Fields must always be fully initialized before any access is given to the object begin created. The initializers can only access static and top-level variables, not any instance variables on the object itself.
With null safety, you will be allowed to write late String jsonText = this.something + this.other;
. That field will then not be initialized until it's first read or written, which is necessarily after the object itself has been created.
Solution 3:[3]
Dart initializes objects in multiple phases. Initializing members directly ("field initializers") occurs early in object initialization, before this
becomes valid, so that phase cannot initialize members that depend on other parts of the object.
Dart provides multiple ways to initialize members, so if one member needs to depend on another, you can initialize it in a later phase by using a different mechanism. For example, you could do one of:
- Add the
late
keyword to make the dependent member lazily initialized. - Move initialization of the dependent member into the constructor body.
- In the case of a Flutter
State
subtype, you could initialize the dependent member in itsinitState
method, which in some cases is more appropriate.
Note that in some cases you additionally can consider replacing the member variable with a read-only getter instead. For example, in your case, perhaps you could use:
String get jsonText => jsonTextPref + jsonTextSuff.toString();
That would be appropriate if jsonText
should always depend on jsonTextPref
and jsonTextSuff
, would never need to have an independent value, and if it's acceptable for jsonText
to return a new object every time it's accessed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Antoniossss |
Solution 2 | lrn |
Solution 3 |