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
.
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 |
Map.update() returns value of type V
.
In this example,
map
with some key-value pairs.update()
method to update the value for the key 'one' by adding 1 to the current value.ifAbsent
parameter is provided to handle the case when the key is not present.map
is printed, showing the updated value for 'one'.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}
}
{one: 2, two: 2}
In this example,
map
with some key-value pairs.update()
method to update the value for the key 2 to 'New Two'.ifAbsent
parameter is not provided, if the key is not present, an error will occur.map
is printed, showing the updated value for key 2.void main() {
Map<int, String> map = {1: 'One', 2: 'Two'};
map.update(2, (value) => 'New Two');
print(map); // Output: {1: One, 2: New Two}
}
{1: One, 2: New Two}
In this example,
map
with some key-value pairs.update()
method to update the value for the non-existing key 'size' to 'medium'.ifAbsent
parameter is provided with a default value of 'small' to handle the case when the key is not present.map
is printed, showing the new entry for 'size'.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}
}
{fruit: apple, color: red, size: medium}
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.