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:
-
At the time of declaration :
int count = 0;
-
In the initializing formals:
Foo(this.count);
-
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.
-
Use the
late
keyword:class Foo { late int count; // No error void bar() => count = 0; }
-
Make variable nullable:
class Foo { int? count; // No error void bar() => count = 0; }