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 its initState
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.