是否有一种方法用于判断对象是否为空,然后决定获取['数据']或什么也不做?
这是错误消息:
引发了以下NoSuchMethodError构建Builder:方法'[]'在null上调用。接收者:null尝试呼叫:
回答问题的最简单方法:
final data = list != null ? list[0] : null;
有一种简写方法可以对任何对象的属性和方法做同样的事情:a?.b
或a?.b()
将首先检查a
,然后分别获取b
或调用b
,如果a
为null则返回null。
这种速记不适用于属性和方法的下标。
回答如何检查null。
您可以使用?.
安全地调用对象上的方法。
List<int> badList;
List<int> goodList = [];
badList.add(1); // error because it is null.
badList?.add(1); // no error because it checked for null
goodList.add(1); // no error
goodList?.add(1); // no error
在列表中回答如何做到这一点
据我所知,没有办法在列表中检查它。
List<int> list;
int value = list[0]; // error
你应该用
List<int> list;
int index = 1;
if (list != null && index < list.length) { // that's how you should check
int value = list[index]; // safe to use list[]
}