0

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?

jamesdlin
  • 65,531
  • 13
  • 129
  • 158
Cassergio
  • 31
  • 1
  • 5

3 Answers3

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.

lrn
  • 51,374
  • 4
  • 81
  • 97
2

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.

jamesdlin
  • 65,531
  • 13
  • 129
  • 158
0

You can only use constant expressions as initializers. x=this.y is not constant.

Antoniossss
  • 28,922
  • 5
  • 49
  • 91
  • Field initializers do not need to be constant. For example, this is valid: `import 'dart:math'; var random = Random(); class Foo { int x = random.nextInt(100); }` – jamesdlin Jun 15 '21 at 18:50
  • You probably got this mixed up with *default values*, which are required to be constant. – jamesdlin Apr 23 '22 at 01:11