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.

Flutter in Production

Flutter in Production

Learn about flavors, environments, error monitoring, analytics, release management, CI/CD, and finally ship your Flutter apps to the stores. ๐Ÿš€

Flutter Foundations Course

Flutter Foundations Course

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

Flutter & Firebase Masterclass

Flutter & Firebase Masterclass

Learn about Firebase Auth, Cloud Firestore, Cloud Functions, Stripe payments, and much more by building a full-stack eCommerce app with Flutter & Firebase.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

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

Flutter Animations Masterclass

Flutter Animations Masterclass

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