What is the cleanest way to get the sum of numbers in a collection/list in Dart?

This is a very old question but

In 2022 there is actually a built-in package.

Just import

import 'package:collection/collection.dart';

and call the .sum extension method on the Iterable.

FULL EXAMPLE

import 'package:collection/collection.dart';

void main() {
  final list = [1, 2, 3, 4];
  final sum = list.sum;
  print(sum); // prints 10
}

If the list is empty, .sum returns 0.

You might also be interested in list.average...


Dart iterables now have a reduce function (https://code.google.com/p/dart/issues/detail?id=1649), so you can do a sum pithily without defining your own fold function:

var sum = [1, 2, 3].reduce((a, b) => a + b);

I still think this is cleaner and easier to understand for this particular problem.

num sum = 0;
[1, 2, 3].forEach((num e){sum += e;});
print(sum);

or

num sum = 0;
for (num e in [1,2,3]) {
  sum += e;
}

int sum = [1, 2, 3].fold(0, (previous, current) => previous + current);

or with shorter variable names to make it take up less room:

int sum = [1, 2, 3].fold(0, (p, c) => p + c);

Tags:

Iteration

Dart