flutter - 为什么 snapshot.data.length 有错误?
问题描述
我正在尝试从 API 解析数据。为此,我使用 FutureBuilder 在 ListView 中列出所有已解析的数据。
我已经检查了 of 的无效性,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(String 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;
}
解决方案
继续这个答案,我找到了解决问题的方法。显然 getData 没有按预期返回 List 。相反,它返回一个对象。
将对象类型转换为列表解决了这个问题。
这是更正后的代码:
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,
);
});
}
},
),
),
推荐阅读
- sql - 对具有不同值的两个字段进行分组,并按顺序选择特定值
- c++ - 在 switch 语句中将多个案例组合在一起
- r - 用 lapply 替换 for 循环
- javascript - AJAX 表单发布,即使它被禁用
- selenium - Selenium moveByOffset 不会将焦点移动到提供的坐标
- html - 改变跨度位置
- r - 结合不同因子水平下的数据,同时保留原始水平
- ios - 尝试从控制器更改该单元格中的 UITextField 时,UICollectionView 中的单元格返回 nil
- php - PHP 警告:xyy::query($query) 的声明应该与 mysqli::query($query, $resultmode = NULL) 兼容
- javascript - 来自可变数组字符串的Highcharts数据值