首页 > 解决方案 > 'bool?' 类型的值 不能分配给“bool”类型的变量。小部件返回值

问题描述

我有一个声明

bool _glutenFree = false;

当我尝试使用如下赋值运算符时

_glutenFree = widget.currentFilters['gluten'];

我收到一条错误消息

'bool?' 类型的值 不能分配给“bool”类型的变量。

检查“widget.currentFilters['gluten']”的值

我尝试使用 print 命令,发现该值为 false。

现在,当我将赋值语句更改为

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

该程序有效。

你能告诉我这个问题吗

标签: flutterdart

解决方案


我自己尝试了一些解决方案。如果我!在最后添加:

_glutenFree = widget.currentFilters['gluten']!

代码会崩溃。

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

是您问题的最佳答案。

如果你使用布尔?_glutenfree 也很好


推荐阅读