Iterables in Dart Programming


Iterables in Dart are a collection of values, or "elements", that we can access in a sequential manner.

The elements of the iterable are accessed by making use of an iterator getter.

There are multiple collections in Dart that implement the Iterables, for example, LinkedList, List, ListQueue, MapKeySet, MapValueSet and much more.

There are different constructors that we can make use of when we want to create an Iterable, like −

  • Iterable() - creates an iterable

  • Iterable.empty() - creates an empty iterable.

  • Iterable.generate() - creates an iterable which generates its elements dynamically.

Example

Let's consider a few examples of Iterables in Dart.

Consider the example shown below −

 Live Demo

void main(){
   var map = new Map();
   map['apple'] = true;
   map['banana'] = true;
   map['kiwi'] = false;

   for(var fruit in map.keys){
      print("the current fruit is : ${fruit}");
   }
}

Output

the current fruit is : apple
the current fruit is : banana
the current fruit is : kiwi

Example

Let's take another example, where we have a LinkedHashSet which also implements an Iterable class.

Consider the example shown below −

 Live Demo

void main(){
   var set = new Set()..add('apple')..add('mango');
   for(var fruit in set){
      print("fruit : ${fruit}");
   }
}

Output

fruit : apple
fruit : mango

Updated on: 21-May-2021

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements