Combine/merge multiple maps into 1 map

Viewed 32285

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"};
5 Answers

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

var finalMap = Map.fromEntries(mapList.expand((map) => map.entries));
 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 "5" will be overwritten with "6".

Related