Working with iterables in Dart
What is an iterable?
An iterable is a collection of elements that can be accessed sequentially. It is a generalization of a list. It is a way to access a collection of objects. It is an object that can be iterated upon. It is an object that implements the Iterable
interface.
What is an iterator?
An iterator is an object that provides access to the elements of an iterable collection. It helps you to loop through the elements of a collection. It is also called a cursor.
Working with iterables
Now, lets create a simple iterable and loop through it to print its elements.
void main () {
// Create an iterable using the Iterable constructor of length 10
var iterable = Iterable<int>.generate(10);
// Loop through the iterable using the for-in loop
for (var element in iterable) {
print(element);
}
}
Output
0
1
2
3
4
5
6
7
8
9
Accessing the elements of an iterable
You can access the elements of an iterable using the the following methods:
elementAt()
methodfirst
propertylast
propertysingle
propertyfirstWhere()
methodlastWhere()
methodsingleWhere()
method
And so on ..
Example
Now, lets access the elements of an iterable.
void main () {
// Create an iterable using the Iterable constructor of length 10
var iterable = Iterable<int>.generate(10);
// Access the elements of the iterable using the elementAt() method
print(iterable.elementAt(0));
print(iterable.elementAt(1));
print(iterable.elementAt(2));
print(iterable.elementAt(3));
Output
0
1
2
3
Iterating over an iterable
You can iterate over an iterable using the following methods:
forEach()
methodmap()
methodwhere()
methodwhereType()
methodexpand()
method
And so on ..
Example
Now, lets iterate over an iterable.
void main () {
// Create an iterable using the Iterable constructor of length 10
var iterable = Iterable<int>.generate(10);
// Iterate over the iterable using the forEach() method
iterable.forEach((element) => print(element));
Output
0
1
2
3
4
5
6
7
8
9
You can use loops like this to iterate over an iterable.
Conclusion
So, in this tutorial, we learned:
- What is an iterable?
- How to create an iterable?
- How to access the elements of an iterable?
- How to iterate over an iterable?