Dart Map addAll()
Syntax & Examples


Syntax of Map.addAll()

The syntax of Map.addAll() method is:

 void addAll(Map<K, V> other) 

This addAll() method of Map adds all key/value pairs of other to this map.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe map whose key/value pairs will be added to this map

Return Type

Map.addAll() returns value of type void.



✐ Examples

1 Merge maps with string keys and integer values

In this example,

  1. We create two maps, map1 and map2, with key/value pairs.
  2. We then use the addAll() method on map1, passing map2 as the argument, to add all key/value pairs from map2 to map1.
  3. We print the updated map1 to standard output.

Dart Program

void main() {
  Map&lt;String, int&gt; map1 = {'apple': 1, 'banana': 2};
  Map&lt;String, int&gt; map2 = {'cherry': 3};
  map1.addAll(map2);
  print('Updated map1: $map1');
}

Output

Updated map1: {apple: 1, banana: 2, cherry: 3}

2 Merge maps with integer keys and string values

In this example,

  1. We create two maps, map1 and map2, with key/value pairs.
  2. We then use the addAll() method on map1, passing map2 as the argument, to add all key/value pairs from map2 to map1.
  3. We print the updated map1 to standard output.

Dart Program

void main() {
  Map&lt;int, String&gt; map1 = {1: 'one', 2: 'two'};
  Map&lt;int, String&gt; map2 = {3: 'three'};
  map1.addAll(map2);
  print('Updated map1: $map1');
}

Output

Updated map1: {1: one, 2: two, 3: three}

3 Merge maps with string keys and string values

In this example,

  1. We create two maps, map1 and map2, with key/value pairs.
  2. We then use the addAll() method on map1, passing map2 as the argument, to add all key/value pairs from map2 to map1.
  3. We print the updated map1 to standard output.

Dart Program

void main() {
  Map&lt;String, String&gt; map1 = {'name': 'John'};
  Map&lt;String, String&gt; map2 = {'age': '30'};
  map1.addAll(map2);
  print('Updated map1: $map1');
}

Output

Updated map1: {name: John, age: 30}

Summary

In this Dart tutorial, we learned about addAll() method of Map: the syntax and few working examples with output and detailed explanation for each example.