Dart出现错误警告疑似Bug:提示操作数不可空但实际为可空类型
Dart可空bool类型分支判断的警告解析
先看你提供的代码:
void main() { bool? b; if(b==true){ print('b is true'); }else if(b==false){ print('b is false'); }else if(b==null){ print('b is null'); }else{ print('nothing!'); } }
程序运行输出符合预期的b is null,但else if(b==null)一行出现警告:The operand can't be null, so the condition is always 'true'.,这不是Dart的bug,是类型系统的正常推断结果。
为什么会出现这个警告?
Dart的静态类型分析会逐步缩小变量的可能取值范围:
- 初始状态下,
b是bool?类型,可能的取值为true、false、null - 当
if(b==true)判断不成立时,进入else分支的b只能是false或null - 再经过
else if(b==false)判断不成立后,后续分支里的b就只剩下null这一种可能了
此时else if(b==null)的判断完全多余——因为b必然是null,所以编译器会提示这个条件永远为真。
怎么解决?
直接把else if(b==null)替换成else即可,逻辑完全等价,还能消除警告:
void main() { bool? b; if(b==true){ print('b is true'); }else if(b==false){ print('b is false'); }else{ print('b is null'); } }
如果使用Dart 3.0及以上版本,也可以用模式匹配简化代码,逻辑更清晰:
void main() { bool? b; switch(b) { case true: print('b is true'); case false: print('b is false'); case null: print('b is null'); } }
内容的提问来源于stack exchange,提问作者Anup Barua
相关产品推荐
相关产品推荐

