How to remap and add extra property in flutter

everyone; recently I was new in flutter and wanted to try to remap the data from firestore.

The data from firestore

[
{name:"john",age:12},
{name:"wick",age:12},
]

Expected Result

[
  {name:"john",age:12,id:xxx},
    {name:"wick",age:12,id:xxx},
]

Is this possible to add new property like this, I try to use map but not working for me. Hope someone could help me and explain it to me. Thanks in advanced!

>Solution :

Yes, it it possible, you need to iterate over it so you can access each item, then use the spread operator ..., or the addAll method of the Map:

void main() {
  List<Map<String, dynamic>> list = [
    {"name": "john", "age": 12},
    {"name": "wick", "age": 12},
  ];

  List<Map<String, dynamic>> newList = actionOn(list);

  print(newList);
}

List<Map<String, dynamic>> actionOn(List<Map<String, dynamic>> list) {
  return list.map((Map<String, dynamic> elem) {
    return {...elem, "age": 12};
  }).toList();
}

Leave a Reply