无法在地图中添加多个数据

时间:2020-09-06 10:57:05

标签: flutter dart

我创建了如下地图:

 Map<String, GenreData> map = new HashMap();

我正在从API获取数据,但是我只在地图中添加了一个数据。api中还有更多数据。

            for (var genderdata in snapshot.data.data.data) {
              hashmap = {genderdata.name:genderdata};

            }

我正在尝试映射名称(值)和工艺(键)。这样我就可以根据CRAFT对NAME进行分类。

这是我的json

   {
    "data": [
        {
            "_id": "5f3d60b5494f5f003e26af7d",
            "name": "Art & Design",
            "craft": "DIGITAL_ARTIST",
            "createdAt": "Wed Aug 19 2020 17:26:13 GMT+0000 (Coordinated Universal Time)",
            "__v": 0,
            "updatedAt": "Tue Sep 01 2020 14:56:25 GMT+0000 (Coordinated Universal Time)",
            "id": "5f3d60b5494f5f003e26af7d"
        },
        {
            "_id": "5f3d6109494f5f003e26af7f",
            "name": "Beauty",
            "craft": "DIGITAL_ARTIST",
            "createdAt": "Wed Aug 19 2020 17:27:38 GMT+0000 (Coordinated Universal Time)",
            "__v": 0,
            "id": "5f3d6109494f5f003e26af7f"
        },
        {
            "_id": "5f3d619e494f5f003e26af87",
            "name": "Hip Hop",
            "craft": "MUSIC",
            "createdAt": "Wed Aug 19 2020 17:30:06 GMT+0000 (Coordinated Universal Time)",
            "__v": 0,
            "updatedAt": "Tue Sep 01 2020 14:59:48 GMT+0000 (Coordinated Universal Time)",
            "id": "5f3d619e494f5f003e26af87"
        },
        {
            "_id": "5f3d621f494f5f003e26af8b",
            "name": "Punk",
            "craft": "MUSIC",
            "createdAt": "Wed Aug 19 2020 17:32:15 GMT+0000 (Coordinated Universal Time)",
            "__v": 0,
            "id": "5f3d621f494f5f003e26af8b"
        },
        {
            "_id": "5f3d6254494f5f003e26af8d",
            "name": "Pop",
            "createdAt": "Wed Aug 19 2020 17:33:08 GMT+0000 (Coordinated Universal Time)",
            "__v": 0,
            "craft": "MUSIC",
            "updatedAt": "Tue Sep 01 2020 15:02:39 GMT+0000 (Coordinated Universal Time)",
            "id": "5f3d6254494f5f003e26af8d"
        },
        {
            "_id": "5f3d62ad494f5f003e26af91",
            "name": "R & B",
            "craft": "MUSIC",
            "createdAt": "Wed Aug 19 2020 17:34:37 GMT+0000 (Coordinated Universal Time)",
            "__v": 0,
            "updatedAt": "Tue Sep 01 2020 15:04:13 GMT+0000 (Coordinated Universal Time)",
            "id": "5f3d62ad494f5f003e26af91"
        }
    ]
}

1 个答案:

答案 0 :(得分:2)

使用= {}清除地图,然后插入当前项目。

相反,使用:

for (var genderData in snapshot.data.data.data) {
  hashmap.putIfAbsent(genderData.name, () => genderData);
}

如果您需要有关putIfAbsent的更多信息,请检查api。还有HashMaphere