如何解决Flutter nullsafety:条件列表位置
如果我不确定一个列表是否为空,我可以这样做
final something = myList?[0].property;
如果我知道 myList
存在但不确定其中是否存在元素怎么办?
我需要手动检查 isNotEmpty 吗?
final something = myList[0]?.property;
说The receiver can't be null,so the null-aware operator '?.' is unnecessary.
解决方法
您需要将列表定义为可以为空。
例如:
List<myObject?> myList = [myObject(),null,myObject()]
// then error is not shown
final something = myList[0]?.property;
示例
void main() {
List<int?> list = null;
for (var i = 0; i< list.length; i++ ) {
print(list[i]?.isEven);
}
// Error: The value 'null' can't be assigned to a variable of type 'List<int?>' because
// 'List<int?>' is not nullable.
// - 'List' is from 'dart:core'.
// List<int?> list = null;
List<int?> list2 = [null,2,1,3,null];
for (var i = 0; i< list2.length; i++ ) {
print(list2[i]?.isEven);
}
// no error
List<int?> list3 = [];
print(list3[5]?.isEven);
//no error
}
,
是的。您需要检查它是否为空。
如果 myList 存在且不为空
late List<dynamic> myList;
myList = [];
if (myList.length > 0){
}
如果 myList 可以为空
late List<dynamic>? myList;
if (myList != null && myList!.length > 0) {
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。