Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-nullable instance field must be initialized

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.

like image 330
iDecode Avatar asked Apr 10 '21 12:04

iDecode


People also ask

What does non-nullable by default mean in Dart?

The Dart language now supports sound null safety! When you opt into null safety, types in your code are non-nullable by default, meaning that variables can't contain null unless you say they can.

What is non-nullable variable?

Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.


1 Answers

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

With null safety, Dart has no way of knowing if you had actually assigned a variable to count. Dart can see initialization in three ways:

  1. At the time of declaration:

    int count = 0; 
  2. In the initializing formals:

    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 at some other point before using it.

  1. Use the late keyword:

    class Foo {   late int count; // No error   void bar() => count = 0; } 
  2. Make variable nullable:

    class Foo {   int? count; // No error   void bar() => count = 0; } 
like image 144
iDecode Avatar answered Oct 14 '22 10:10

iDecode