In Dart, an iterable is any object that can provide a sequence of values. It's a fundamental concept in Dart's collection library and is widely used in Dart programming. Dart provides built-in support for iterables through various classes and interfaces, making it easy to work with collections of data.
var numbers = [1, 2, 3, 4, 5];
var uniqueNumbers = {1, 2, 3, 4, 5};
var keyValuePairs = {'a': 1, 'b': 2, 'c': 3};
for (var number in numbers) {
print(number);
}
numbers.forEach((number) => print(number));
var doubledNumbers = numbers.map((number) => number * 2);
print(doubledNumbers.toList()); // Output: [2, 4, 6, 8, 10]
var evenNumbers = numbers.where((number) => number % 2 == 0);
print(evenNumbers.toList()); // Output: [2, 4]
Iterable < int> countTo(int n) sync* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
void main() {
var sequence = countTo(5);
print(sequence.toList()); // Output: [1, 2, 3, 4, 5]
}
var combinedList = [...numbers, ...evenNumbers];
print(combinedList); // Output: [1, 2, 3, 4, 5, 2, 4]
var doubledEvenNumbers = [for (var num in evenNumbers) num * 2];
print(doubledEvenNumbers); // Output: [4, 8]
var lazySequence = numbers.map((number) {
print('Doubling $number');
return number * 2;
});
print('Lazy sequence created');
print(lazySequence.take(2).toList()); // Output: Doubling 1, Doubling 2