【发布时间】:2022-12-10 06:54:52
【问题描述】:
即使下面的代码已经检查了t.s!=null,dart 仍然会抛出错误:
t.dart:7:26: Error: Property 'length' cannot be accessed on 'String?' because it is potentially null. Try accessing using ?. instead. if (t.s != null && t.s.length > 5) {}
class Test {
String? s;
}
void main() {
Test t = Test();
if (t.s != null && t.s.length > 5) {}
}
添加额外的 var 将解决它如下:
void main() {
Test t = Test();
var s = t.s;
if (s != null && s.length > 5) {}
}
为什么即使 t.s!=null 已经检查过,dart 也会抛出错误?
有没有办法在不添加额外的var的情况下做到这一点?
此外,在 Typescript 中,它不会抛出错误:
function main(t:{s?:string}){
if(t.s!==undefined && t.s.length > 5){
}
}
【问题讨论】:
标签: dart dart-null-safety