Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Map increment the value of a key

Tags:

flutter

dart

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

like image 911
Jrod Avatar asked Nov 28 '25 18:11

Jrod


1 Answers

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}
}
like image 135
Ardent Coder Avatar answered Dec 01 '25 10:12

Ardent Coder