skip to Main Content

the code is this:

Map<String, Object> _ordini = {};
    
//widget._ordini is a List<Map>
widget._ordini.forEach((element) {
_ordini.addAll(element);
});
print(_ordini);
    

in _orders I will find only the last element.
I also tried:

Map<String, Object> _ordini = {};
    
  //widget._ordini is a List<Map>
  widget._ordini.forEach((element) {
  Map<String, Object> _temp = {};
 _temp.addAll(element);
_ordini.addAll(_temp);
 });
    
print(_ordini);

but the problem still remains.

2

Answers


  1. As @OMiShah
    mentioned:

    If a key of other is already in this map, its value is overwritten

    but one thing you can do is sum the values like this:

    lets assume this is your:

    List<Map<String, int>> ordini = [
          {
            "String1": 1,
          },
          {
            "String1": 2,
          },
          {
            "String3": 3,
          }
        ];
    

    you can try this:

    ordini.forEach((element) {
      element.entries.forEach((e) {
        if (_ordini.containsKey(e.key)) {
          _ordini[e.key] = _ordini[e.key]! + e.value;
        } else {
          _ordini[e.key] = e.value;
        }
      });
    });
    
     print(_ordini); //{String1: 3, String3: 3}
    

    this is just an example to give you an idea to some how solve that issue.

    Login or Signup to reply.
  2. Here is the answer of your question.

    When you do .addAll() means at one moment it will remove everything from the list and add all new elements.

    So, if you want to add one by one then you can use .addEntries({})

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search