类型 'Null' 不是类型转换中类型 'bool' 的子类型
type 'Null' is not a subtype of type 'bool' in type cast
我在 flutter 中创建了一个 Map(其中键是 String 类型,值是 Boolean 类型)当我想在 if 条件下使用 bool 值时它给我错误说“可空表达式不能用作条件。
在将其用作条件之前,请尝试检查该值是否不是 'null'。”
当我使用“as bool”时,错误消失了,但程序没有正确执行,并在 pic
中给我错误
//this is the code
Map<String, bool> _userFilters = {
"gluten": false,
"lactose": false,
"vegan": false,
"vegetarian": false,
};
List<Meal> filteredMeal = DUMMY_MEALS;
void saveFilters(Map<String, bool> filteredData) {
setState(() {
_userFilters = filteredData;
filteredMeal = DUMMY_MEALS.where(
(meal) {
if (_userFilters['gluten']as bool) { // _userFilter['gluten'] is giving error
return false;
}
if (_userFilters['lactose']as bool) {
return false;
}
if (_userFilters['vegan']as bool) {
return false;
}
if (_userFilters['vegetarian'] as bool) {
return false;
}
return true;
},
).toList();
});
}
enter image description here
无需将地图条目转换为布尔值。在变量的末尾使用感叹号(例如, _usedFilters['gluten']!
)将其视为不可为空。
像这样重写所有条件(如果您确定该值不会为空):
if (_userFilters['gluten']!) {
return false;
}
if (_userFilters['lactose']!) {
return false;
}
if (_userFilters['vegan']!) {
return false;
}
if (_userFilters['vegetarian']!) {
return false;
}
来自Dart.dev:
“Casting away nullability” comes up often enough that we have a new
shorthand syntax. A postfix exclamation mark (!) takes the expression
on the left and casts it to its underlying non-nullable type.
我在 flutter 中创建了一个 Map
//this is the code
Map<String, bool> _userFilters = {
"gluten": false,
"lactose": false,
"vegan": false,
"vegetarian": false,
};
List<Meal> filteredMeal = DUMMY_MEALS;
void saveFilters(Map<String, bool> filteredData) {
setState(() {
_userFilters = filteredData;
filteredMeal = DUMMY_MEALS.where(
(meal) {
if (_userFilters['gluten']as bool) { // _userFilter['gluten'] is giving error
return false;
}
if (_userFilters['lactose']as bool) {
return false;
}
if (_userFilters['vegan']as bool) {
return false;
}
if (_userFilters['vegetarian'] as bool) {
return false;
}
return true;
},
).toList();
});
}
enter image description here
无需将地图条目转换为布尔值。在变量的末尾使用感叹号(例如, _usedFilters['gluten']!
)将其视为不可为空。
像这样重写所有条件(如果您确定该值不会为空):
if (_userFilters['gluten']!) {
return false;
}
if (_userFilters['lactose']!) {
return false;
}
if (_userFilters['vegan']!) {
return false;
}
if (_userFilters['vegetarian']!) {
return false;
}
来自Dart.dev:
“Casting away nullability” comes up often enough that we have a new shorthand syntax. A postfix exclamation mark (!) takes the expression on the left and casts it to its underlying non-nullable type.