What is the cleanest way to get the sum of numbers in a collection/list in Dart?
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);
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);
This is a very old question but
In 2021 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
...