小编典典

Flutter / Dart如何分组按地图列表

flutter

我有这张地图清单。

[
    {title: 'Avengers', release_date: '10/01/2019'},
    {title: 'Creed', release_date: '10/01/2019'}
    {title: 'Jumanji', release_date: '30/10/2019'},
]

我想编写一个这样的代码来对电影列表进行分组release_date

[
   {
      "10/01/2019": [
         {
            "title": "Avengers"
         },
         {
            "title": "Creed"
         }
      ]
   },
   {
      "30/10/2019": [
         {
            "title": "Jumanji"
         }
      ]
   }
]

阅读 698

收藏
2020-08-13

共1个答案

小编典典

集合实现该groupBy功能。

对于按日期分组:

import "package:collection/collection.dart";

main(List<String> args) {
  var data = [
    {"title": 'Avengers', "release_date": '10/01/2019'},
    {"title": 'Creed', "release_date": '10/01/2019'},
    {"title": 'Jumanji', "release_date": '30/10/2019'},
  ];


  var newMap = groupBy(data, (obj) => obj['release_date']);

  print(newMap);
}

release_date要从每个地图条目中删除密钥:

var newMap = groupBy(data, (obj) => obj['release_date']).map(
    (k, v) => MapEntry(k, v.map((item) { item.remove('release_date'); return item;}).toList()));

更改密钥:

var newMap = groupBy(data, (obj) => obj['release_date']).map(
    (k, v) => MapEntry(k, v.map((item) => {'name': item['title']}).toList()));
2020-08-13