What is map.update() in Dart?

map.update()

In Dart, the map.update() method is a built-in method that updates the value associated with a specific key.

Syntax

V update (K key, V update(V value), { V ifAbsent() })

If the key is present, the new value is stored in the map.

If the key is missing and ifAbsent() is specified, the function calls ifAbsent() and adds the key to the map with the specified value.

If the key isn’t present and ifAbsent() isn’t specified, an error occurs.

Return type

The method map.update() returns the key’s updated value.

Code

void main() {
// Creating Map named map
Map map = {1: 'Orange', 2: 'Apple', 3: 'watermelon'};
print('The original map: ${map}');
// Updating value for key 1
map.update(1, (v) {
print('The previous value for key 1 before update: ' + v);
return 'Pawpaw';
});
print('The new map: ${map}');
}

Now, suppose the key 1 is not present in the map. If we try to update, we’ll get an error. To avoid this error, we’ll use the ifAbsent() method.

void main() {
// Creating Map named map
Map map = {2: 'Apple', 3: 'watermelon'};
print('The original map: ${map}');
// Updating value for key 1
// If absent, add the value and key
map.update(1, (v) => 'Orange', ifAbsent: () => 'Lemon');
print('The new map: ${map}');
}

Free Resources