flutter 如何将列表转换为Map形式并得到这样的结果?

4ktjp1zp  于 2022-11-30  发布在  Flutter
关注(0)|答案(2)|浏览(252)

如何将列表转换为Map形式并获得如下结果:

{"data":[{"id_pet":"63","id_habit":0},{"id_pet":"64","id_habbit":0}]}

我的代码:

event.listPet.asMap();

我的清单:

↓   pet: List (2 items)
  ↓ [0]: Pet
    id_pet: 1
    id_habbit: 1
  ↓ [1]: Pet
    id_pet: 2
    id_habbit: 2
kyxcudwk

kyxcudwk1#

return {"data": event.listPet.map((e) => e.toMap()).toList(),};

您应该确保在Pet类中定义了toMap方法。

0pizxfdo

0pizxfdo2#

使用fromIterable

Map<String, dynamic> map1 = {
    "id_pet":"63",
    "id_habit": 0
  };
  
   Map<String, dynamic> map2 = {
    "id_pet":"64",
    "id_habit": 0
  };
  List<Map<String, dynamic>> list = [];
    
  list.add(map1);
  list.add(map2);
  
  var map3 = Map.fromIterable(list, key: (e) => "data", value: (e) => list);
  print(map3);

相关问题