map.update()
In Dart, the map.update()
method is a built-in method that updates the value associated with a specific key.
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 andifAbsent()
isn’t specified, an error occurs.
The method map.update()
returns the key’s updated value.
void main() {// Creating Map named mapMap map = {1: 'Orange', 2: 'Apple', 3: 'watermelon'};print('The original map: ${map}');// Updating value for key 1map.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 mapMap map = {2: 'Apple', 3: 'watermelon'};print('The original map: ${map}');// Updating value for key 1// If absent, add the value and keymap.update(1, (v) => 'Orange', ifAbsent: () => 'Lemon');print('The new map: ${map}');}