【发布时间】:2020-05-15 15:46:33
【问题描述】:
我基本上来自 JS 背景,现在正在尝试使用 Flutter 框架。 我一直在格式化从 API 收到的数据。
Data 接收到一个对象数组
[
{
"id": 1,
"name": "name1",
"type": "Both",
"count": 4
},
{
"id": 2,
"name": "name2",
"type": "Both",
"count": 6
},
{
"id": 3,
"name": "name1",
"type": "Both",
"count": 2
},
{
"id": 4,
"name": "name3",
"type": "Both",
"count": 8
},
......
]
我的要求是我必须根据名称对数据进行分组
{
name1: [
{
"id": 1, "name":"name1", "type": "Both", "count": 4
},
{
"id": 3, "name":"name1", "type": "Both", "count": 2
}
],
name2: [
{
"id": 2, "name":"name2", "type": "Both", "count": 6
}
],
.....
}
在 dart 中,我已经设法使用 collections.dart 包中的 groupBy 进行分组。
问题是我无法遍历分组数据。我需要访问计数以对每个分组名称进行一些操作。
以下是我尝试过的代码片段
Map data;
List partySnapData;
Map newMap;
Future _getTopParties() async {
final response =await http.get(API_URL + '/getPartySnapShot');
data =json.decode(response.body);
partySnapData = data['resultObj'];
setState(() {
newMap = groupBy(partySnapData, (obj) => obj['party_name']);
for(var v in newMap.values) {
print(v);
}
});
}
print(v) 实际上给了我映射到地图 E.G 的值
[
{ "id": 1, "name":"name1", "type": "Both", "count": 4 },
{ "id": 3, "name":"name1", "type": "Both", "count": 2 }
],
.....,
......
现在,我如何循环或迭代数组,这里是 v,以便我可以访问里面的元素?
【问题讨论】: