Non-nullable instance field must be initialized

Total
0
Shares
Table of Contents Hide
  1. Solution
    1. Related Posts:
class Foo {
  int count; // Error
  void bar() => count = 0;
}

Why I’m seeing an error when I’am already initializing it in the bar method? I could understand this error if count was marked final.


Solution

(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 can see initialization in three ways:

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;

So, according to Dart, count was never initialized in your code and hence the error. The solution is to either initialize it in 3 ways shown above or just use the late keyword which will tell Dart that you are going to initialize the variable later.

4. Use the late keyword:

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

5. Make variable nullable:

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

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *