I don't like using an indexed array for no reason other than I think it looks ugly. Is there a clean way to sum with an anonymous function? Is it possible to do it without using any outside variables?
14 Answers
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);

- 2,161
- 1
- 16
- 15
-
40This fails if the list is empty. `.fold()` handles that case. – Gazihan Alankus Jul 22 '19 at 14:51
-
getting error `Uncaught Error: Bad state: No element` if `List` is empty. I have checked `List.length` before `var sum = [1, 2, 3].reduce((a, b) => a + b);` statement and it worked for me. Thanks. – Kamlesh Jun 26 '21 at 08:27
-
Had an issue when working with custom objects e.g. Object.amount – wamae Jul 12 '21 at 09:36
-
5This answer is outdated. Please consider this https://stackoverflow.com/a/68603277/8539278 – tmaihoff Aug 03 '21 at 20:41
-
You can use this to handle empty list too: [1, 2, 3].fold(0, (e, t) => e + t); – M Karimi Jan 17 '23 at 15:10
-
You can use fold to handle empty list too: [1, 2, 3].fold(0, (e, t) => e + t); – M Karimi Jan 17 '23 at 15:11
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);

- 1,967
- 1
- 14
- 13
-
2This should be the accepted answer as it is more generalizable to work on empty lists. – Ryan Deschamps Jan 15 '21 at 15:40
-
20I prefer this answer.. why does reduce even exist?! Me: I want `.fold` Mom: We already have `.fold` at home `.fold` at home: `.reduce` – SEG.Veenstra Feb 11 '21 at 08:36
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
...

- 2,867
- 1
- 18
- 40
-
Is it possible to use this method to add all the numbers up to a certain index in the list? – Ariel H. Aug 07 '22 at 13:03
-
2Sure, you can write `list.sublist(0,3).sum`, which sums up from index 0 until exluding index 3 – tmaihoff Aug 08 '22 at 09:42
-
Also, every Iterable has a `.take(int count)` method, letting you omit the lower "0" boundary and creating a lazy iterator instead of a list (which might be more performant if you don't need all items as you do with the "sum" getter) – David Schneider Sep 05 '22 at 09:37
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;
}

- 1,310
- 11
- 17
There is not a clean way to do it using the core libraries as they are now, but if you roll your own foldLeft then there is
main() {
var sum = foldLeft([1,2,3], 0, (val, entry) => val + entry);
print(sum);
}
Dynamic foldLeft(Collection collection, Dynamic val, func) {
collection.forEach((entry) => val = func(val, entry));
return val;
}
I talked to the Dart team about adding foldLeft to the core collections and I hope it will be there soon.

- 20,275
- 13
- 66
- 83
-
This could be addressed by adding an inject function to the collection interface like in Ruby. – Mark B May 02 '12 at 02:51
-
1That's some very pretty code there, Lars. Not only was it what I was looking for, now I understand folding. – Phlox Midas May 02 '12 at 07:20
-
1You can certainly do it with an anonymous function, with or without any library code to do it, just by inlining the code in foldLeft above. And you're pretty much always going to need a variable, unless you're excessively clever with recursion. Alternatively, you can also just do it with a for(var each in...) rather than forEach, and apply the function in the body of the for loop. Either works. – Alan Knight May 02 '12 at 12:47
-
2Note that there are already some external libraries for working with collections -- some of them were mentioned in this thread: http://groups.google.com/a/dartlang.org/group/misc/browse_thread/thread/0628027441ad1ac8/329810f9fa00a866 Also the collections library is undergoind severe changes currently, I hope that sum (or at least fold/reduce) is coming right into it. – Ladicek May 03 '12 at 06:31
Starting with Dart 2.6 you can use extensions to define a utility method on the List. This works for numbers (example 1) but also for generic objects (example 2).
extension ListUtils<T> on List<T> {
num sumBy(num f(T element)) {
num sum = 0;
for(var item in this) {
sum += f(item);
}
return sum;
}
}
Example 1 (sum all the numbers in the list):
var numbers = [1, 2, 3];
var sum = numbers.sumBy((number) => number);
Example 2 (sum all the Point.x fields):
var points = [Point(1, 2), Point(3, 4)];
var sum = points.sumBy((point) => point.x);

- 34,185
- 17
- 113
- 116
-
1hi, are extension methods ready yet? I just tried to enable them by adding the experiments flag (dart 2.6.1) but then lost intellisense and received a dart analyser exception in IntelliJ. Any ideas? – atreeon Nov 26 '19 at 11:56
-
@atreeon I don't remember adding any flag but remember to update your Flutter, Dart plugins to latest versions and also double check that you're actually using at least version 2.6.0. Also the extension class (ListUtils in this case) needs to be imported in the file where you're trying to use it. – vovahost Nov 26 '19 at 12:00
-
I was using it in a stand alone Dart app, I've just upgraded to the latest Flutter and it says I have 2.5 (I think there are different version for the flutter install to what is run on the comman line)...so, the latest version of Flutter uses 2.5??? I am so confused! – atreeon Nov 26 '19 at 12:25
-
I'd just like to add some small detail to @tmaihoff's answer (about using the collection.dart package):
The sum
getter he talks about only works for iterables of num
values, like List<int>
or Set<double>
.
If you have a list of other object types that represent values (like Money
, Decimal
, Rational
, or any others) you must map it to numbers. For example, to count the number of chars in a list of strings you can do:
// Returns 15.
['a', 'ab', 'abc', 'abcd', 'abcde'].map((e) => e.length).sum;
As of 2022, another way of doing it, is using the sumBy()
method of the fast_immutable_collections package:
// Returns 15.
['a', 'ab', 'abc', 'abcd', 'abcde'].sumBy((e) => e.length), 15);
Note: I'm the package author.

- 29,013
- 23
- 109
- 133
I suggest you to create this function in any common utility file.
T sum<T extends num>(T lhs, T rhs) => lhs + rhs;
int, double, float extends num class so you can use that function to sum any numbers.
e.g.,
List<int> a = [1,2,3];
int result = a.reduce(sum);
print(result); // result will be 6

- 41
- 2
Herewith sharing my Approach:
void main() {
int value = sumTwo([1, 4, 3, 43]);
print(value);
}
int sumTwo(List < int > numbers) {
int sum = 0;
for (var i in numbers) {
sum = sum + i;
}
return sum;
}

- 2,730
- 6
- 12
- 27

- 226
- 3
- 9
If when using fold gives a double
TypeError, you can use reduce:
var sum = [0.0, 4.5, 6.9].reduce((a, b) => a + b);

- 3,842
- 2
- 23
- 36
If you are planning on doing a number of mathematical operations on your list, it may be helpful to create another list type that includes .sum() and other operations by extending ListBase. Parts of this are inspired by this response with performance tweaks from this response.
import 'dart:collection';
import 'dart:core';
class Vector<num> extends ListBase<num> {
List<num> _list;
Vector() : _list = new List<num>();
Vector.fromList(List<num> lst): _list = lst;
void set length(int l) {
this._list.length=l;
}
int get length => _list.length;
num operator [](int index) => _list[index];
void operator []=(int index, num value) {
_list[index]=value;
}
// Though not strictly necessary, for performance reasons
// you should implement add and addAll.
void add(num value) => _list.add(value);
void addAll(Iterable<num> all) => _list.addAll(all);
num sum() => _list.fold(0.0, (a, b) => a + b) as num;
/// add additional vector functions here like min, max, mean, factorial, normalize etc
}
And use it like so:
Vector vec1 = Vector();
vec1.add(1);
print(vec1); // => [1]
vec1.addAll([2,3,4,5]);
print(vec1); // => [1,2,3,4,5]
print(vec1.sum().toString()); // => 15
Vector vec = Vector.fromList([1.0,2.0,3.0,4.0,5.0]); // works for double too.
print(vec.sum().toString()); // => 15

- 351
- 4
- 16
A solution that has worked cleanly for me is:
var total => [1,2,3,4].fold(0, (e, t) => e + t); // result 10

- 1,417
- 1
- 11
- 14
Different ways to find the sum of all dart list elements,
Method 1: Using a loop : This is the most commonly used method. Iterate through the list using a loop and add all elements of the list to a final sum variable. We are using one for loop here :
main(List<String> args) {
var sum = 0;
var given_list = [1, 2, 3, 4, 5];
for (var i = 0; i < given_list.length; i++) {
sum += given_list[i];
}
print("Sum : ${sum}");
}
Method 2: Using forEach : forEach is another way to iterate through a list. We can also use this method to find out the total sum of all values in a dart list. It is similar to the above method. The only difference is that we don’t have to initialize another variable i and list.length is not required.
main(List<String> args) {
var sum = 0;
var given_list = [1, 2, 3, 4, 5];
given_list.forEach((e) => sum += e);
print("Sum : ${sum}");
}
Method 3: Using reduce : reduce method combines all elements of a list iteratively to one single value using a given function. We can use this method to find out the sum of all elements as like below :
main(List<String> args) {
var given_list = [1, 2, 3, 4, 5];
var sum = given_list.reduce((value, element) => value + element);
print("Sum : ${sum}");
}
Method 4: Using fold : fold() is similar to reduce. It combines all elements of a list iteratively to one single value using a function. It takes one initial value and calculates the final value based on the previous value.
main(List<String> args) {
var sum = 0;
var given_list = [1,2,3,4,5];
sum = given_list.fold(0, (previous, current) => previous + current);
print("Sum : ${sum}");
}
for more details:https://www.codevscolor.com/dart-find-sum-list-elements

- 1,387
- 11
- 13
extension DoubleArithmeticExtensions on Iterable<double> {
double get sum => length == 0 ? 0 : reduce((a, b) => a + b);
}
extension IntArithmeticExtensions on Iterable<int> {
int get sum => length == 0 ? 0 : reduce((a, b) => a + b);
}
Usage:
final actual = lineChart.data.lineBarsData[0].spots.map((s) => s.x).sum;

- 6,770
- 5
- 51
- 103