我正在尝试解析API中的数据。为此,我使用FutureBuilder列出ListView中所有已解析的数据。
我已经检查了snapshot.data
的无效性,但是我一直在snapshot.data.length
段中得到这个错误,它说,The property 'length' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').
我在snapshot.data[i]
部分也有一个类似的错误,上面写着The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').
下面是我的代码的相同部分:
body: Container(
child: FutureBuilder(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return ListTile(
title: snapshot.data[i].partOfSpeech,
);
});
}
},
),
),
下面是getData(字符串s):
Future<List> getData(String s) async {
var response = await http
.get(Uri.https('api.dictionaryapi.dev', 'api/v2/entries/en_US/' + s));
var jsonData = jsonDecode(response.body)[0];
List<Data> data = [];
for (var x in jsonData["meanings"]) {
String definition = x["definitions"][0]["definition"];
Data d = Data(x["partOfSpeech"], definition);
data.add(d);
}
return data;
}
发布于 2021-07-02 14:38:04
如果你正在使用一个新版本的颤振(2.2.0或更高)。首先,尝试向目标('!')添加一个空检查。因为空安全特性。
body: Container(
child: FutureBuilder(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, i) {
return ListTile(
title: snapshot.data[i].partOfSpeech,
);
});
}
},
),
),
然后尝试将FutureBuilder类型指定为数据类型列表
body: Container(
child: FutureBuilder<List<Data>>(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return ListTile(
title: snapshot.data[i].partOfSpeech,
);
});
}
},
),
),
发布于 2021-06-30 10:44:08
作为对这个answer的继续,我找到了解决问题的方法。显然,getData没有按预期返回列表。相反,它是返回一个对象。
类型化对象列表解决了问题。
以下是修正后的代码:
body: Container(
child: FutureBuilder(
future: getData('hello'),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
//typecasting Object to List
var data = (snapshot.data as List<Data>).toList();
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, i) {
return ListTile(
title: data[i].partOfSpeech,
);
});
}
},
),
),
发布于 2022-03-16 10:22:15
将'AsyncSnapshot‘放在构建器参数的快照之前。
builder: (context, AsyncSnapshot snapshot)
https://stackoverflow.com/questions/68174647
复制相似问题