To merge two maps in Dart, you can use the addAll() method to add key-value pairs from one map to another. This method provides a straightforward way to combine the contents of two maps.
We can merge two maps in Dart using the addAll() method, which adds all key-value pairs from one map to another.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values.addAll()
method to add all key-value pairs from map2
to map1
.print
function to verify the merge.void main() {
// Declare and initialize two maps
Map<String, int> map1 = {'one': 1, 'two': 2};
Map<String, int> map2 = {'three': 3, 'four': 4};
// Merge map2 into map1
map1.addAll(map2);
// Print the merged map
print('Merged Map: $map1');
}
Merged Map: {one: 1, two: 2, three: 3, four: 4}
We can merge two maps in Dart and handle overlapping keys by using the addAll()
method, which updates the values for overlapping keys.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values, and there is an overlapping key.addAll()
method to add all key-value pairs from map2
to map1
.print
function to verify the merge.void main() {
// Declare and initialize two maps with overlapping keys
Map<String, int> map1 = {'one': 1, 'two': 2};
Map<String, int> map2 = {'two': 22, 'three': 3};
// Merge map2 into map1, updating values for overlapping keys
map1.addAll(map2);
// Print the merged map
print('Merged Map: $map1');
}
Merged Map: {one: 1, two: 22, three: 3}
We can also merge two maps in Dart using the spread operator, which provides a concise way to combine the contents of two maps.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values.map1
and map2
.print
function to verify the merge.void main() {
// Declare and initialize two maps
Map<String, int> map1 = {'one': 1, 'two': 2};
Map<String, int> map2 = {'three': 3, 'four': 4};
// Merge the maps using the spread operator
Map<String, int> mergedMap = {...map1, ...map2};
// Print the merged map
print('Merged Map: $mergedMap');
}
Merged Map: {one: 1, two: 2, three: 3, four: 4}
In this tutorial, we learned How to Merge Two Maps in Dart language with well detailed examples.