Dart: How to Add new Key/Value Pairs to a Map

Last updated on August 17, 2021 A Goodman Loading... Post a comment

This short article shows you a few ways to add new key/value pairs to a given map in Dart (and Flutter as well).

Using map[newKey] = newValue syntax

Example:

// main.dart
Map<String, dynamic> map = {
  'key1': 'Dog',
  'key2': 'Chicken',
  'key3': 'Kindacode.com',
  'key4': 'Buffalo'
};

void main() {
  map['key5'] = 'Blue';
  map['key6'] = 'Green';
  map['some_key'] = 'Hey Bro';

  print(map);
}

Output:

{
  key1: Dog, 
  key2: Chicken, 
  key3: Kindacode.com, 
  key4: Buffalo, 
  key5: Blue, 
  key6: Green, 
  some_key: Hey Bro
}

Using addAll() method

This method can be used to combine 2 different maps. It will add all key/value pairs of a map to another map. If a key already exists, its value will be overwritten.

Example:

// main.dart
Map<String, dynamic> map1 = {'key1': 'A', 'key2': 'B', 'key3': 'C'};
Map<String, dynamic> map2 = {'key3': '3', 'key4': '4', 'key5': '5'};

void main() {
  map1.addAll(map2);
  print(map1);
}

Output:

{
  key1: A, 
  key2: B, 
  key3: 3, // This value is overwritten
  key4: 4, 
  key5: 5
}

Using addEntries() method

This method is used to add a collection of key/value pairs to a given map. Like the addAll() method, when a key is already in the map, its value will be overwritten.

Example:

// main.dart
Map<String, dynamic> map = {'key1': 'A', 'key2': 'B', 'key3': 'C'};

void main() {
  map.addEntries([
    MapEntry('key3', 'A new value'),
    MapEntry('key4', 'D'),
    MapEntry('key5', 'E'),
    MapEntry('key6', 'Kindacode.com')
  ]);
  print(map);
}

Output:

{
  key1: A, 
  key2: B, 
  key3: A new value, 
  key4: D, 
  key5: E, 
  key6: Kindacode.com
}

Conclusion

We’ve gone through a couple of different ways to add new entries to a given map in Dart. These techniques might be very useful for you when working with data-intensive apps. If you’d like to learn more about modern Dart and Flutter, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like