I have a declaration

bool _glutenFree = false;

When I try to use an assignment operator as below

_glutenFree = widget.currentFilters['gluten'];

I get an error message

A value of type 'bool?' can't be assigned to a variable of type 'bool'.

To check the value of "widget.currentFilters['gluten']"

I tried using the print command and found that the value is false.

Now when I change the assignment statement to

_glutenFree = widget.currentFilters['gluten'] == true;

The program works.

Could you please enlighten me with the issue

Solution 1: Deepak Lohmod

_glutenFree = widget.currentFilters['gluten']!;

try this as for null safety you need to add'!'.

Solution 2: OMi Shah

It should be bool? _glutenFree = false;

Notice the ? after the bool type. It represents that the variable _glutenFree can be null.

Currently, the currentFilters can return nullable or a value of type bool and your variable currentFilters is declared as a non-nullable type of bool.

For more info on Dart's Sound null safety head to https://dart.dev/null-safety

Solution 3: Mirza Talha

I tried few of the solutions myself. If I add ! at the end like:

_glutenFree = widget.currentFilters['gluten']!

code will crash.


_glutenFree = widget.currentFilters['gluten'] ?? false; 

is the best possible answer to your problem.

If you use bool? _glutenfree that is fine as well

Solution 4: Shahood ul Hassan

You should use _glutenFree = widget.currentFilters['gluten'] ?? false;.

?? means that if widget.currentFilters['gluten'] returns null, return false, otherwise return whatever value was returned by widget.currentFilters['gluten'].

So, in a sense, we provided a default value of false to return in case the returned value was null.

Hope it helps!