Dart Map update()
Syntax & Examples


Syntax of Map.update()

The syntax of Map.update() method is:

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

This update() method of Map updates the value for the provided key.

Parameters

ParameterOptional/RequiredDescription
keyrequiredthe key whose value is to be updated
updaterequiredthe function that provides the new value based on the current value
ifAbsentoptionalthe default value to use if the key is not present in the map

Return Type

Map.update() returns value of type V.



✐ Examples

1 Update value for existing key

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the update() method to update the value for the key 'one' by adding 1 to the current value.
  3. The ifAbsent parameter is provided to handle the case when the key is not present.
  4. The updated map map is printed, showing the updated value for 'one'.

Dart Program

void main() {
  Map<String, int> map = {'one': 1, 'two': 2};
  map.update('one', (value) => value + 1, ifAbsent: () => 0);
  print(map); // Output: {one: 2, two: 2}
}

Output

{one: 2, two: 2}

2 Update value for existing key without ifAbsent

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the update() method to update the value for the key 2 to 'New Two'.
  3. Since the ifAbsent parameter is not provided, if the key is not present, an error will occur.
  4. The updated map map is printed, showing the updated value for key 2.

Dart Program

void main() {
  Map<int, String> map = {1: 'One', 2: 'Two'};
  map.update(2, (value) => 'New Two');
  print(map); // Output: {1: One, 2: New Two}
}

Output

{1: One, 2: New Two}

3 Update value for non-existing key with ifAbsent

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the update() method to update the value for the non-existing key 'size' to 'medium'.
  3. The ifAbsent parameter is provided with a default value of 'small' to handle the case when the key is not present.
  4. The updated map map is printed, showing the new entry for 'size'.

Dart Program

void main() {
  Map<String, String> map = {'fruit': 'apple', 'color': 'red'};
  map.update('size', (value) => 'medium', ifAbsent: () => 'small');
  print(map); // Output: {fruit: apple, color: red, size: medium}
}

Output

{fruit: apple, color: red, size: medium}

Summary

In this Dart tutorial, we learned about update() method of Map: the syntax and few working examples with output and detailed explanation for each example.