Dart Iterables: Operations on Iterables

Dart Iterables: Operations on Iterables

ยท

2 min read

In Dart, iterables are objects that can be iterated (looped) through. Dart provides several useful operations and methods to work with iterables. Here are some common operations:

1. forEach:

  • Applies a function to each element of the iterable.
List<int> numbers = [1, 2, 3, 4, 5];

numbers.forEach((int number) {
  print(number);
});

2. map:

  • Transforms each element of the iterable using a function.
List<int> numbers = [1, 2, 3, 4, 5];

List<String> stringNumbers = numbers.map((int number) {
  return 'Number: $number';
}).toList();

3. where:

  • Filters elements based on a condition.
List<int> numbers = [1, 2, 3, 4, 5];

List<int> evenNumbers = numbers.where((int number) {
  return number % 2 == 0;
}).toList();

4. any:

  • Checks if any element satisfies a given condition.
List<int> numbers = [1, 2, 3, 4, 5];

bool hasEvenNumber = numbers.any((int number) {
  return number % 2 == 0;
});

5. every:

  • Checks if every element satisfies a given condition.
List<int> numbers = [1, 2, 3, 4, 5];

bool allEvenNumbers = numbers.every((int number) {
  return number % 2 == 0;
});

6. toList, toSet:

  • Converts the iterable to a List or Set.
List<int> numbers = [1, 2, 3, 4, 5];

List<int> numbersList = numbers.toList();
Set<int> numbersSet = numbers.toSet();

7. reduce:

  • Combines the elements of the iterable using a provided function.
List<int> numbers = [1, 2, 3, 4, 5];

int sum = numbers.reduce((value, element) => value + element);

8. fold:

  • Similar to reduce, but allows specifying an initial value.
List<int> numbers = [1, 2, 3, 4, 5];

int sum = numbers.fold(0, (value, element) => value + element);

These operations provide powerful ways to manipulate and transform iterables in Dart. Depending on your use case, you can choose the appropriate operation to achieve the desired result.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย