How to Combine Multiple Maps in Flutter/Dart
1 min readJan 6, 2024
In this example, you will learn to combine or merge two or more maps in one map in Flutter or Dart. Sometimes, you may need to combine multiple hasMap into one map while building the mobile app. See the example below:
Map mapa = {
"a":"Apple",
"b":"Ball",
"c":"Cat"
};
Map mapb = {
"d":"Dog",
"e":"Egg",
"f":"Flag"
};
Map mapc = {
"g":"Goat",
"h":"Hen",
"i":"ink"
};
These maps will be used in the following examples.
Method 1: addAll for two Maps:
Map comb1 = {};
comb1.addAll(mapa);
comb1.addAll(mapb);
print(comb1);
//{a: Apple, b: Ball, c: Cat, d: Dog, e: Egg, f: Flag}
This is the primary method to combine two maps in Dart or Flutter.
Method 2: addAll with More than Two Maps:
Map comb2 = {};
comb2..addAll(mapa)..addAll(mapb)..addAll(mapc);
print(comb2);
//{a: Apple, b: Ball, c: Cat, d: Dog, e: Egg, f: Flag, g: Goat, h: Hen, i: ink}
This is the way, you can combine two or more two maps together into one map.
Method 3: Single Line Method:
Map comb3 = {...mapa, ...mapb, ...mapc};
print(comb3);
//{a: Apple, b: Ball, c: Cat, d: Dog, e: Egg, f: Flag, g: Goat, h: Hen, i: ink}
This is the shortest way to combine two or more maps into a single map.