23.3 C
New York
Wednesday, August 17, 2022

Flutter & Dart: fold() method examples

- Advertisement -

Some common use cases of the fold() method in Dart (and Flutter as well).

Calculating the sum of a list

void main() {
  final myList = [1, 3, 5, 8, 7, 2, 11];
  final result = myList.fold(0, (sum, element) => sum + element);
  
  print(result);
}

Output:Advertisements

37

Finding the biggest number in a list

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);
}

Output:

11

Find the smallest number in a list

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);
}

Output:

2

Wrap Up

We’ve gone over some examples of using the fold() method in Dart programs. If you’d like to explore more about Dart and Flutter development, take a look at the following articles:

AdvertisementsYou can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.

Advertisements
- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles