Reputation: 551
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"))!;
Questions: Why is the error reported in 2 places? I would prefer to use the 2nd form (with the !), but I can't
Thanks
Upvotes: 0
Views: 118
Reputation: 1144
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.
Upvotes: 2
Reputation: 884
if you're using shared_preferences, getBool
is nullable, and you're assigning it to a non nullable bool. If you want to fix your linting error you should make fff
nullable as well:
bool? fff = preferences?.getBool("_wantSpaces");
Or have a default value like you stated earlier:
bool fff = preferences?.getBool("_wantSpaces") ?? false;
Upvotes: 1