-3

How to convert a list into map form and get results like this:

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

My code:

event.listPet.asMap();

My list:

↓   pet: List (2 items)
  ↓ [0]: Pet
    id_pet: 1
    id_habbit: 1
  ↓ [1]: Pet
    id_pet: 2
    id_habbit: 2
My Car
  • 4,198
  • 5
  • 17
  • 50
  • 1
    can you include your original list that you wanna convert – Gwhyyy Nov 29 '22 at 04:39
  • Does this answer your question? [How to convert a List into a Map in Dart](https://stackoverflow.com/questions/16831535/how-to-convert-a-list-into-a-map-in-dart) – OMi Shah Nov 29 '22 at 04:50

2 Answers2

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

You should make sure toMap method is defined in your Pet class.

Rahul
  • 3,529
  • 1
  • 5
  • 19
-1

use 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);
Jungwon
  • 1,038
  • 7
  • 20