Dart: Calculate the Sum of all Values in a Map

Last updated on July 4, 2022 A Goodman Loading... Post a comment

This short article shows you a few ways to find the sum of all values in a given map in Dart (presume that all the values are numbers).

Using a For/In loop

Example:

// main.dart
void main() {
  const Map<String, double> prices = {
    'priceOne': 9.9,
    'priceTwo': 20.5,
    'priceThree': 45,
    'priceFour': 30.88
  };

  double sum = 0;

  // get the list of all values of the map
  List<double> values = prices.values.toList();

  // calculate the sum with a loop
  for (double value in values) {
    sum += value;
  }

  // print out the sum
  print(sum);
}

Output:

106.28

Using Reduce() function

Example:

// main.dart
void main() {
  const Map<String, double> map = {
    'value1': 9,
    'value2': 9.9,
    'value3': 14,
    'value4': 15.5,
    'value5': 20
  };

  Iterable<double> values = map.values;

  final result = values.reduce((sum, value) => sum + value);
  print(result);
}

Output:

68.4

That’s it. Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like