How to Combine Multiple Maps in Flutter/Dart

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.

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.

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.

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.

This way, you can combine two or more maps into one in Dart or Flutter.

No any Comments on this Article


Please Wait...