Dart – Iterable

Iterable

Iterable is an extract class, it can’t de instantiate directly.

An Iterable of string and int

void main() {
Iterable<int> var1 = [1,2,3,4];
Iterable<String> var2 = ['a','b','c','d'];
}

The difference with List and Iterable is that that element in the list can be accessed with their index value using [] operator while in Iterable value can’t be accessed using [] operator.

void main() {
Iterable<int> var1 = [1,2,3,4];
Iterable<String> var2 = ['a','b','c','d'];
print(var1[1]);
}

If we run the above program. We get the operator error.

Error compiling to JavaScript:
main.dart:4:13:
Error: The operator '[]' isn't defined for the class 'Iterable<int>'.
- 'Iterable' is from 'dart:core'.
print(var1[1]);
^
Error: Compilation failed.

Correct program:

void main() {
Iterable<int> var1 = [1,2,3,4];
Iterable<String> var2 = ['a','b','c','d'];
print(var1.elementAt(1));
}

Output: 2

Using for loop to print element of iterable

void main() {
Iterable<int> var1 = [1, 2, 3, 4];
for (var element in var1) {
print(element);
}
}

Performing few operations:

void main() {
Iterable<int> var1 = [1, 2, 3, 4];
print(var1.first);
print(var1.last);
print(var1.length);
print(var1.contains(1));
print(var1.skip(1));
print(var1.single);

}

OutPut:

1
4
4
true
(2, 3, 4)
Uncaught Error: Bad state: Too many elements

firstreturn the first element, last return the last element, length return the length of iterable, contains(1) return the element at position 1, skip(1) skip the element at position 1, single return the element if iterable has only one element. Throw this error if it has more than one element or empty Uncaught Error: Bad state: Too many elements .

Leave a comment

Your email address will not be published. Required fields are marked *