Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

What is map.update() in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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}');
}

RELATED TAGS

dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring