Non-nullable instance field must be initialized

(Your code was fine before Dart 2.12, null safety)

With null safety, Dart doesn’t know if you actually assigned a value to count. Dart initializes objects in two phases, and Dart expects all member variables to already be initialized when the constructor’s body executes. Because your members are non-nullable and haven’t been initialized to non-null values yet, this is an error.

1. At the time of declaration:

int count = 0;

2. In the initializing formals parameters:

Foo(this.count);

3. In the initializer list:

Foo() : count = 0;

4. Use the late keyword:

This means that you promise that the variables will be initialized before anything attempts to use them.

class Foo {
  late int count; // No error
  void bar() => count = 0;
}

5. Make the variable nullable:

class Foo {
  int? count; // No error
  void bar() => count = 0;
}

However, that will require that all accesses explicitly check that the members aren’t null before using them.


Also see: Dart assigning to variable right away or in constructor?

Leave a Comment