'Combine/merge multiple maps into 1 map

How can I combine/merge 2 or more maps in dart into 1 map? for example I have something like:

 var firstMap = {"1":"2"};
 var secondMap = {"1":"2"};
 var thirdMap = {"1":"2"};

I want:

 var finalMap = {"1":"2", "1":"2", "1":"2"};


Solution 1:[1]

you can use addAll method of Map object

var firstMap = {"1":"2"};
var secondMap = {"2":"3"};

var thirdMap = {};

thirdMap.addAll(firstMap);
thirdMap.addAll(secondMap);

print(thirdMap);

Or

var thirdMap = {}..addAll(firstMap)..addAll(secondMap);

Update

Since dart sdk 2.3 You can use spread operator ...

final firstMap = {"1":"2"};
final secondMap = {"2":"3"};

final thirdMap = {
   ...firstMap,
   ...secondMap,
};

Solution 2:[2]

alternate syntax using Map.addAll, Iterable.reduce and cascading operator, for combining a lot of maps:

var combinedMap = mapList.reduce( (map1, map2) => map1..addAll(map2) );

live dartpad example https://dartpad.dartlang.org/9cd116d07d2f45a9b890b4b1186dcc5e

Solution 3:[3]

Another option is using CombinedMapView from package:collection:

new CombinedMapView([firstMap, secondMap])

It doesn't create a merged map, but creates a Map that is a view of both.

Solution 4:[4]

I came up with a "single line" solution for an Iterable of Maps:

var finalMap = Map.fromEntries(mapList.expand((map) => map.entries));

Solution 5:[5]

 var firstMap = {"1":"5"};
 var secondMap = {"1":"6"};
 var thirdMap = {"2":"7"};
 
 var finalMap = {...firstMap, ...secondMap, ...thirdMap};
 // finalMap: {"1":"6", "2":"7"};

Notice that key "1" with value "2" will be overwritten with "6".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dafe Šimonek
Solution 3 Eray Erdin
Solution 4 SdtElectronics
Solution 5 MrHIDEn