Dart Iteratable

Dart Iteratable

ยท

2 min read

In Dart, an iterable is an object that represents a sequence of elements that can be iterated (looped) through. Dart provides various iterable classes, and common ones include List, Set, and Map. Additionally, Dart has iterable constructs like Iterable and Iterator that provide methods and functionality for iterating through collections.

Here's an overview:

Iterable Classes:

  1. List:

    • A collection of ordered elements.
    List<int> numbers = [1, 2, 3, 4, 5];
  1. Set:

    • A collection of unordered, unique elements.
    Set<String> fruits = {'apple', 'banana', 'orange'};
  1. Map:

    • A collection of key-value pairs.
    Map<String, int> ages = {'Alice': 25, 'Bob': 30, 'Charlie': 22};

Iterable Operations:

  1. forEach:

    • Iterates over each element in the iterable.
    List<int> numbers = [1, 2, 3];
    numbers.forEach((number) {
      print(number);
    });
  1. map:

    • Creates a new iterable by applying a function to each element.
    List<int> numbers = [1, 2, 3];
    List<String> result = numbers.map((number) => 'Number: $number').toList();
  1. where:

    • Creates a new iterable with elements that satisfy a condition.
    List<int> numbers = [1, 2, 3, 4, 5];
    List<int> evenNumbers = numbers.where((number) => number % 2 == 0).toList();
  1. toList, toSet, toMap:

    • Converts an iterable to a List, Set, or Map.
    List<int> numbers = [1, 2, 3];
    Set<int> numberSet = numbers.toSet();

Iterating with for-in Loop:

The for-in loop is commonly used for iterating over iterables:

List<int> numbers = [1, 2, 3];
for (var number in numbers) {
  print(number);
}

Iterating with Iterable and Iterator:

The Iterable class provides methods for working with collections, and Iterator is used to iterate through elements manually.

List<int> numbers = [1, 2, 3];
Iterable<int> iterableNumbers = numbers;
Iterator<int> iterator = iterableNumbers.iterator;

while (iterator.moveNext()) {
  print(iterator.current);
}

Iterables provide a powerful way to work with collections in Dart, offering various methods for transformation, filtering, and iteration. Understanding how to use iterables is fundamental for effective Dart programming.

Did you find this article valuable?

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

ย