Jrod
Jrod

Reputation: 43

Dart Map increment the value of a key

I'm currently working with a Map in which the values are of type integer but I need to update the value of a key every time an action takes place. Example: if the Map is { "key1": 1 } after the actions takes place it should be {"key1":2} and so on. Here's my code:

void addToMap(Product product) {
    if (_order.containsKey(product.name)) {
      _order.update(product.name, (int) => _order[product.name]+1);
    }
    _order[product.name] = 1;
  }

Where _order is the Map

Upvotes: 3

Views: 3527

Answers (2)

Ardent Coder
Ardent Coder

Reputation: 3985

You may use the following idiomatic approach in Dart:

map.update(
    key,
    (value) => ++value,
    ifAbsent: () => 1,
  );

This uses the built-in update method along with the optional ifAbsent parameter that helps set the initial value to 1 when the key is absent in the map. It not only makes the intent clear but also avoids pitfalls like that of forgetting to place the return statement that had been pointed out in the other answer.

Additionally, you may also wrap up the above method as an Extension to Map<dynamic, int>. This way also makes the call site look much less cluttered, as visible from the following demo:

extension CustomUpdation on Map<dynamic, int> {
  int increment(dynamic key) {
    return update(key, (value) => ++value, ifAbsent: () => 1);
  }
}

void main() {
  final map = <String, int>{};
  map.increment("foo");
  map.increment("bar");
  map.increment("foo");
  print(map); // {foo: 2, bar: 1}
}

Upvotes: 7

Michael Yuwono
Michael Yuwono

Reputation: 2617

Add return or the map will always get overridden by _order[product.name] = 1;

void addToMap(Product product) {
  if (_order.containsKey(product.name)) {
    _order.update(product.name, (int) => _order[product.name]+1);
    return;
  }
  _order[product.name] = 1;
}

Upvotes: 3

Related Questions