Dart: How to Update a Map

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

This short article shows you 3 ways to update a map in Dart (and Flutter as well).

1 – Using map[key] = [newValue] syntax

This approach is straightforward and makes the code easy to read and write.

Example:

// main.dart
Map<String, dynamic> person = {
  'firstName': 'John',
  'lastName': 'Doe',
  'age': 45,
  'spouse': 'Jane Doe',
  'children': 3,
  'nationality': 'Unknown'
};

void main() {
  person['nationality'] = 'United States';
  person['spouse'] = 'KindaCode.com';
  person['children'] = 5;

  print(person);
}

Output:

{
  firstName: John, 
  lastName: Doe, 
  age: 45, 
  spouse: KindaCode.com, 
  children: 5, 
  nationality: United States
}

2 – Using update() method

This built-in method will update the value associated with a given key.

map.update(key, (value) => newValue)

Example:

// main.dart
Map<String, dynamic> map1 = {
  'key1': 'Kindacode.com',
  'key2': 'Blue',
  'key3': 'Green',
  'key4': 'Orange'
};

void main() {
  map1.update('key3', (value) => 'Transparent');
  map1.update('key4', (value) => 'Something New');
  print(map1);
}

Output:

{
  key1: Kindacode.com, 
  key2: Blue, 
  key3: Transparent, 
  key4: Something New
}

3 – Using updateAll() method

Example

This example will update the values of the map by their squared:

// main.dart
Map<String, dynamic> map2 = {'key1': 1, 'key2': 3, 'key3': 9, 'key4': 18};

void main() {
  map2.updateAll((key, value) => value * value);
  print(map2);
}

Output:

{
  key1: 1, 
  key2: 9, 
  key3: 81, 
  key4: 324
}

What’s Next?

Further reading:

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