Dart map - get sum of all values in Map

Hi Guys, Welcome to Proto Coders Point, In this short article let’s learn how to add all integer values of map and get the sum of them.

The below Snippet of calculating sum of all the values works only if the values in map are number(So will assume all the values in map are numbers).

Learn more about dart map <– Here .

Example 1: Get Sum of all values from Map using Dart Reduce() in-built function

void main() {
  
  const Map<String,int> dataMap = {
    'prodPrice1': 5,
    'prodPrice2': 1,
    'prodPrice3': 6,
    'prodPrice4': 10,
    'prodPrice5': 15,
    'prodPrice6': 4,
  };
  
  Iterable<int> priceValue = dataMap.values;
  
  final sumOfAllPrice = priceValue.reduce((sum,currentValue)=>sum+currentValue);
  
  print(sumOfAllPrice);
}

Output:

41


Example 2: Get Sum of all values from Map using Dart For Loop

void main() {
  
  const Map<String,double> dataMap = {
    'prodPrice1': 55.6,
    'prodPrice2': 2.1,
    'prodPrice3': 6.8,
    'prodPrice4': 10.8,
    'prodPrice5': 19.2,
    'prodPrice6': 44.5,
  };
  double sumOfAllPrice = 0;
  
  // create a list which contain only price value
  List<double> allPriceValueList = dataMap.values.toList();
  
  
  // loop through the list and calculate sum of them
  for(double value in allPriceValueList){
    sumOfAllPrice += value;
  }
  
  print(sumOfAllPrice);
}

Output:

139