rozerro
rozerro

Reputation: 7156

The instance member 'name' can't be accessed in an initializer

I get the error, when declaring a _disposers variable.

The instance member 'name' can't be accessed in an initializer.

class FormStore = _FormStore with _$FormStore;

abstract class _FormStore with Store {

  @observable
  String name = '';

  List<ReactionDisposer> _disposers = [
    reaction((_) => name, validateUsername), // error on name and on validateUsername
  ];

  // ...

It prompts

Try replacing the reference to the instance member with a different expression

Why there is the error and why this error disapears if put late before List<ReactionDisposer> _disposers?

Upvotes: 0

Views: 1098

Answers (1)

Leo Lamas
Leo Lamas

Reputation: 198

You can't initialize an instance member like _disposers using other instance members (like name) because dart doesn't let you use a reference to "this" in initializers.

https://dart.dev/tools/diagnostic-messages#implicit_this_reference_in_initializer

When you use late it becomes lazy, which means it will get initialized/evaluated only when needed (usually when you call it).

Upvotes: 1

Related Questions