如何避免在Flutter中调用null的[]

问题描述 投票:1回答:2

是否有一种方法用于判断对象是否为空,然后决定获取['数据']或什么也不做?

这是错误消息:

引发了以下NoSuchMethodError构建Builder:方法'[]'在null上调用。接收者:null尝试呼叫:

dart flutter
2个回答
1
投票

回答问题的最简单方法:

final data = list != null ? list[0] : null;

有一种简写方法可以对任何对象的属性和方法做同样的事情:a?.ba?.b()将首先检查a,然后分别获取b或调用b,如果a为null则返回null。

这种速记不适用于属性和方法的下标。


0
投票

回答如何检查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[]
}
© www.soinside.com 2019 - 2024. All rights reserved.