地图的奇怪行为(可以为空的表达式不能用作条件)
Weird behavior with Maps(A nullable expression can't be used as a condition)
Map<String,bool> map= { "key1":true, "key2":false };
/*
* Flags following compilation error:
* A nullable expression can't be used as a condition.
* Try checking that the value isn't 'null' before using it as a condition.
*/
if(map["key1"]) {
//do sth
}
/*So I try checking value isn't null as specified in error
*Still flags same compilation error
*/
if(map!=null && map["key1"]) {
//do sth
}
//This works
if(map["key1"] == true) {
//do sth
}
}
根据以下代码片段,我可以知道为什么第一个和第二个 if
块都失败但第三个没有吗?
您误解了错误信息。
A nullable expression can't be used as a condition.
表示你不能做:
bool? condition;
if (condition) {
...
}
Map<K, V>
的operator[]
returns一个V?
。它 returns 是一种可空类型,作为在找不到密钥时指示失败的一种方式,您需要检查返回值不是 null
,而不是 map
本身不是 null
。例如:
if (map["key"] ?? false) {
...
}
您的第三种方法(检查 == true
)有效,因为如果查找 returns null
,它将执行 null == true
相等性检查。但是,您应该更喜欢使用 ?? false
,因为它能更好地传达意图,并且针对 true
或 false
的相等性检查通常是一种代码味道。
Map
上的 []
运算符可以 return null
这使得它可以为空,这在此处有详细解释:https://dart.dev/null-safety/understanding-null-safety#the-map-index-operator-is-nullable
因此您的第一个示例无效,因为 null
不是 bool
。因此,您不能直接将 []
运算符的值用于 Map
.
您的第二个示例由于 map["key1"]
是 bool?
的相同原因而无效。
第三个示例有效,因为 null == true
始终是 false
。因此,进行涉及 null
.
的比较是完全有效的
Map<String,bool> map= { "key1":true, "key2":false };
/*
* Flags following compilation error:
* A nullable expression can't be used as a condition.
* Try checking that the value isn't 'null' before using it as a condition.
*/
if(map["key1"]) {
//do sth
}
/*So I try checking value isn't null as specified in error
*Still flags same compilation error
*/
if(map!=null && map["key1"]) {
//do sth
}
//This works
if(map["key1"] == true) {
//do sth
}
}
根据以下代码片段,我可以知道为什么第一个和第二个 if
块都失败但第三个没有吗?
您误解了错误信息。
A nullable expression can't be used as a condition.
表示你不能做:
bool? condition;
if (condition) {
...
}
Map<K, V>
的operator[]
returns一个V?
。它 returns 是一种可空类型,作为在找不到密钥时指示失败的一种方式,您需要检查返回值不是 null
,而不是 map
本身不是 null
。例如:
if (map["key"] ?? false) {
...
}
您的第三种方法(检查 == true
)有效,因为如果查找 returns null
,它将执行 null == true
相等性检查。但是,您应该更喜欢使用 ?? false
,因为它能更好地传达意图,并且针对 true
或 false
的相等性检查通常是一种代码味道。
Map
上的 []
运算符可以 return null
这使得它可以为空,这在此处有详细解释:https://dart.dev/null-safety/understanding-null-safety#the-map-index-operator-is-nullable
因此您的第一个示例无效,因为 null
不是 bool
。因此,您不能直接将 []
运算符的值用于 Map
.
您的第二个示例由于 map["key1"]
是 bool?
的相同原因而无效。
第三个示例有效,因为 null == true
始终是 false
。因此,进行涉及 null
.