Why are Dart null-safety problems showing up inconsistently in 2 places


I have a flutter app. I’m using VSCode. When I do the following I get the following error reported in two places (the ‘PROBLEMS’ area and in the ‘Debug Console’:

faulty code:

bool fff = (preferences?.getBool("_wantSpaces"));

error msg:

"message": "A value of type ‘bool?’ can’t be assigned to a variable of type ‘bool’.\nTry changing the type of the variable, or casting the right-hand type to ‘bool’.",

If I modify the code like this both errors go away:
good code:

bool fff = (preferences?.getBool("_wantSpaces")) ?? false;

But, if I modify the code like this only the error in the ‘Problems’ goes away:
half good code:

bool fff = (preferences?.getBool("_wantSpaces"))!;

Why is the error reported in 2 places?
I would prefer to use the 2nd form (with the !), but I can’t



This is because you used ? on preferences which means it can be null. So if preferences become null somehow, getBool does not work and the whole thing will be null, but what you are telling the compiler here is (preferences?.getBool("_wantSpaces"))! which means this whole value will never be null, but that is just not true because preferences is nullable as you defined it and therefore the whole thing have the possibility to be null.

Answered By – Benyamin

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.