Launch Offer

Flutter Foundations Course

Buy now and get 25% off the regular price!

View Course

How to update a Map of key-value pairs in Dart

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.

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!

Want More?

Invest in yourself with my high-quality Flutter courses.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Fully updated to Dart 2.15.

The Complete Flutter Course Bundle

The Complete Flutter Course Bundle

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a full-stack Flutter eCommerce app on iOS, Android, and web.

Flutter Animations Masterclass - Full Course

Flutter Animations Masterclass - Full Course

Master Flutter animations and build a completely custom habit tracking application.