'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.



Solution 1:[1]

(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;
    }
    

Solution 2:[2]

These are new rules about Dart about null safety

class Note {
  late int _id;
  late String _title;
  late String? _description;
  late String _date;
  late int _priority;
}

make sure before your variable put late

Solution 3:[3]

Use the late keyword to initialize a variable when it is first read, rather than when it's created.

    class Questionz {late String questionText;late bool questionAnswer;Questionz({required String t, required bool a}) {
questionText = t;
questionAnswer = a;}}

enter image description here

Solution 4:[4]

IN my case i found giving ? and ! to the variable helpful:

 double? _bmi; // adding ? to the double 

  String calculateBMI(){

    _bmi=weight/pow(height/100, 2);
     return  _bmi!.toStringAsFixed(1);// adding ! to the private variable


}

 String getResult(){
    if(_bmi!>=25){ //adding ! to the private variable
     return 'Overweight';
     } else if (_bmi!>=18.5)
   {
      return 'normal';
    }else{return 'underweight';}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 TuGordoBello
Solution 3 iDecode
Solution 4 iamSri