Dart/Flutter - Calculate Sum of Numbers in a List

This tutorial shows you how to get the sum of all numbers in a List using Dart.

If you have some numeric values stored in a List, getting the sum of all values can be done in several ways. Below is a List of integer values that we are going to get the sum of. You can also apply the methods below if the elements are a subtype of num which include int and double.

  var numbers = [1, 2, 3, 4, 5];

Using For Loop

For loop is a common way to iterate over an Iterable. You can use it to get the sum of numbers. First, create a numeric variable to store the result. In each iteration, add the element to the variable using += operator.

  var numbers = [1, 2, 3, 4, 5];

Output:

  15

Using Reduce

reduce is a method that reduces the elements of an Iterable to a single value by combining each element using a provided function. The function accepts two arguments. The first one is the accumulated value whose initial value is the first element. The other is the current element. In order to get the value, you can pass a function that returns the sum of the accumulated value and the current element.

  var result = numbers.reduce((a, b) => a + b);
  print(result);

Output:

  15

Using Fold

fold is similar to reduce. The difference is it accepts an initial value as the first argument, while the accumulator function becomes the second argument.

  var result = numbers.fold(0, (a, b) => a + b);
  print(result);

Output:

  15

Using collection Extension

Dart team's collection package has IterableNumberExtension whose one of the properties is sum. You can install the package by using dart pub add collection (or flutter pub add collection for Flutter).

By importing the collection library using package:collection/collection.dart, you can use the sum getter on any Iterable of numbers.

  print(numbers.sum);

Output:

  15

If you don't want to add an additional library. You can also create your own extension.

  extension MyIterableNumberExtension on Iterable {
    num get sum {
      num sum = 0;
  
      for (var n in this) {
        sum += n;
      }
      
      return sum;
    }
  }

Summary

Getting the sum of numeric elements can be done in several ways. All the methods in this tutorial should have the same complexity as they need to iterate over all the elements. You can choose the one that you prefer to be used in your code.

You can also read about: