A common requirement when working with maps is to:
- Update the value if a given key already exists
- Set the value if it doesn't
You may be tempted to implement some conditional logic to handle this:
class ShoppingCart {
final Map<String, int> items = {};
void add(String key, int quantity) {
if (items.containsKey(key)) {
// item exists: update it
items[key] = quantity + items[key]!;
} else {
// item does not exist: set it
items[key] = quantity;
}
}
}
Alternatively, a shorter version would be:
class ShoppingCart {
final Map<String, int> items = {};
void add(String key, int quantity) {
// add 0 if items[key] does not exist
items[key] = quantity + (items[key] ?? 0);
}
}
Either way, the code is not very readable.
sponsor

Build Flutter Apps Fast. Build an end-to-end Flutter + Firebase app using FlutterFlow and download the code or deploy directly to the app stores. Click to view our new development playground.
And the update()
method offers a simpler (and more expressive) way of doing the same thing: ๐
class ShoppingCart {
final Map<String, int> items = {};
void add(String key, int quantity) {
items.update(
key,
(value) => quantity + value,
ifAbsent: () => quantity,
);
}
}
Learn more here: Map.update() method.
Happy coding!
A common requirement when working with maps is to:
— Andrea Bizzotto ๐ (@biz84) April 20, 2022
- Update the value if a given key already exists
- Set the value if it doesn't
You may be tempted to implement some conditional logic to handle this.
But the update() method offers a simpler way of doing the same thing: ๐ pic.twitter.com/7UMrqnARxd