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

 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!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...