This succinct, practical 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:
// kindacode.com
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:
// kindacode.com
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
This method helps you to update all the values of a map based on a certain formula or algorithm.
Example
This example will update the values of the map by their squared:
// kindacode.com
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?
Keep the ball rolling and stay on track by exploring more about Flutter and Dart:
- Dart & Flutter: 2 Ways to Count Words in a String
- Base64 encoding and decoding in Dart (and Flutter)
- Dart: Sorting Entries of a Map by Its Values
- How to remove items from a list in Dart
- Dart: Convert Timestamp to DateTime and vice versa
- Dart & Flutter: Get the Index of a Specific Element in a List
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.