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

iDecode
  • 22,623
  • 19
  • 99
  • 186

5 Answers5

146

(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?

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
iDecode
  • 22,623
  • 19
  • 99
  • 186
8

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;
    }
}
pableiros
  • 14,932
  • 12
  • 99
  • 105
0

Using the "?" modifier to make the field nullable, allowing it to be uninitialized This method is mostly preferred! Refer to the following code snippet for an example.

String? myField;
-2

in pubspec.yaml if you are using : environment: sdk: ">=2.12.0 <3.0.0"

change to environment: sdk: ">=2.7.0 <3.0.0"

2.12.0 null safety feature is on & 2.7.0 null safety feature is off

tip : instead of copy change manually

for more info https://dart.dev/null-safety

for null safety use ? after variable like var a? and while using the variable use ! after variable , like : if(a!){}

Milind Gour
  • 113
  • 9
  • 3
    So, you're basically telling me to opt out of null safety? Sorry, this isn't something I was looking for ! – iDecode Aug 03 '21 at 06:49
  • your call bro ...I didn't want null safety in project amd got the same error – Milind Gour Aug 03 '21 at 06:51
  • for nulll safety use ? after variable like var a? and while using , use ! after variable ,like : if(a!) – Milind Gour Aug 03 '21 at 06:52
  • 2
    First, how long can you stay there without null safety? Second, I've already provided that solution in my answer. – iDecode Aug 03 '21 at 06:53
  • my error was , due to await and then in ascyn function , I was getting value from another class , which returns future , soo the error was you can't return a variable with ? because of await and then .... – Milind Gour Aug 03 '21 at 07:05
  • 4
    It appears this answer was flagged as _Not an Answer_. It very much _is_ an answer. It is an answer with undesirable side effects—but that's why it's been downvoted, which is the correct action for answers that aren't useful. Answers that provide a sincere effort at answering the question should not be deleted (unless, of course, they are just a link). – Jeremy Caney Oct 08 '21 at 18:11
-2

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';}
iamSri
  • 7
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 29 '21 at 14:46