You can do some interesting things using dart fold() function like sum of some values, the largest or smallest number from a list,
In Flutter using dart fold() method solves a problem where you want to add or accumulate collective information.
For if you have a list of integers and you wanna add all the items from the list and return the value then fold() method is very useful.
List<int> time = [5, 10, 5, 3, 5];
int totalTime(){
int total = time.fold(0, (prev, cur)=>prev+cur));
return total;
}
In the above function, the return value would 28. So the fold() function adds up the value in a loop. It takes one item value (cur) each time and adds with the previous value and saves in prev.
In this prev has an initial value which is 0.
Find the largest number
void main() {
final myList = [1, 3, 5, 8, 7, 2, 11];
final result = myList.fold(myList.first, (max, element){
if(max < element) max = element;
return max;
});
print(result);
}
Find the smallest number
void main() {
final myList = [10, 3, 5, 8, 7, 2, 11];
final result = myList.fold(myList.first, (min, element){
if(min > element) min = element;
return min;
});
print(result);
}