DEV Community

Cover image for Using Fold method in dart
OLUWAYEMI FISAYO NATHANIEL
OLUWAYEMI FISAYO NATHANIEL

Posted on

Using Fold method in dart

The fold method in dart is used for:
Reducing a collection to a single value by iteratively combining each element of the collection with an existing value

Uses [initialValue] as the initial value, then iterates through the elements and updates the value with each element using the [combine] function, as if by:

var value = initialValue;
for (E element in this) {
value = combine(value, element);
}
return value;

The fold method in dart just acts like the reduce method in javascript

Another example of the fold method in dart :
double get totalNetSpend {
return groupedTransactionData.fold(0.0, (sum, item) {
return sum + (item['amount'] as double);
});
}

Top comments (1)

Collapse
 
nsilva1 profile image
Neto Ukpong

this is awesome