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
Parameter | Optional/Required | Description |
---|---|---|
key | required | the key whose value is to be updated |
update | required | the function that provides the new value based on the current value |
ifAbsent | optional | the 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,
- We create a map
map
with some key-value pairs. - We use the
update()
method to update the value for the key 'one' by adding 1 to the current value. - The
ifAbsent
parameter is provided to handle the case when the key is not present. - 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,
- We create a map
map
with some key-value pairs. - We use the
update()
method to update the value for the key 2 to 'New Two'. - Since the
ifAbsent
parameter is not provided, if the key is not present, an error will occur. - 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,
- We create a map
map
with some key-value pairs. - We use the
update()
method to update the value for the non-existing key 'size' to 'medium'. - The
ifAbsent
parameter is provided with a default value of 'small' to handle the case when the key is not present. - 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.