[英]Flutter : get data from nested json null
I have this JSON data from an API:我有来自 API 的 JSON 数据:
[
{
"date": "2021-02-10",
"matches": [
{
"id": 1,
"home": "Turkey",
"away": "Italy",
"h_goals": 0,
"a_goals": 0,
"predect": [
{
"id": 3,
"user_id": 10,
"match_id": 1,
"h_predect": 1,
"a_predect": 1,
"point": 0,
}
]
},
]
I made service to get data without model and create some condition:我做了服务来获取没有 model 的数据并创造了一些条件:
Future userPredects(username, token) async {
try {
List dataList = [];
var response = await http.get(url + 'matches/$username', headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
var data = jsonDecode(response.body);
for (var item in data) {
var count = 0;
for (var match in item['matches']) {
count = count + match['predect'].length;
}
if (count > 0) {
dataList.add(item);
}
}
return dataList;
} catch (e) {
print(e);
}
}
I used it in future builder and get all data just those inside predect object:我在未来的构建器中使用了它,并获得了预测 object 中的所有数据:
How can I solve it?我该如何解决?
return FutureBuilder(
future: mathesProv.userPredects(username, token),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var item = snapshot.data[index];
return Card(
margin: EdgeInsets.only(top: 10, bottom: 10),
child: Column(
children: [
Text('${item['date']}'),
for (var i = 0; i < item['matches'].length; i++)
child: Row(
children: [
Text('${item['matches'][i]['home']}'),
Text('${item['matches'][i]['predect'][0]['h_predect']}'),
the problem is item['matches'][i]['home'] get data correctly but item['matches'][i]['predect'][0]['h_predect'] get null问题是 item['matches'][i]['home'] 正确获取数据,但 item['matches'][i]['predect'][0]['h_predect'] 得到 null
Your API returns JsonArray
not JsonObject
so that is List
not Map
.您的 API 返回JsonArray
而不是JsonObject
所以List
不是Map
。
To get first element use first index:要获取第一个元素,请使用第一个索引:
item[0]['matches'][i]['home']
item[0]['matches'][i]['predect'][0]['h_predect']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.