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

Level up your Flutter app’s performance. Get full visibility into your Flutter app’s performance, including crashes, exceptions in Dart, network health, custom traces, and more. Solve your trickiest issues, optimize user journeys, and wow your end users - again and again.
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!