skip to Main Content

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

2

Answers


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

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

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search