Imagine you have a bunch of things, like numbers or words, that you want to work with in your Dart program.
These things could be organized in different ways, like in a list (imagine it as a shopping list), a set (imagine it as a collection of unique items), or even a stream (imagine it as a continuous flow of information).
Now, Dart gives you a handy tool called an "iterable" to deal with these collections of things.
An iterable is basically a way to go through each item in your collection, one by one, and do something with it.
By embracing Iterables, developers can write concise and expressive code to perform various operations such as mapping, filtering, and reducing data.
Mapping Elements
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Map each number to its square
var squares = numbers.map((number) => number * number);
print(squares); // Output: (1, 4, 9, 16, 25)
}
Filtering Elements
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Filter out even numbers
var oddNumbers = numbers.where((number) => number % 2 != 0);
print(oddNumbers); // Output: (1, 3, 5)
}
Reducing Elements
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Calculate the sum of all numbers
var sum = numbers.reduce((value, element) => value + element);
print(sum); // Output: 15
}