The `expand` method in Dart expands each element of the Iterable into zero or more elements.
The syntax of Runes.expand() method is:
Iterable<T> expand<T>(Iterable<T> f(int element))
This expand() method of Runes expands each element of this Iterable into zero or more elements.
Parameter | Optional/Required | Description |
---|---|---|
f | required | A function that takes an element of the Iterable and returns an Iterable. |
Runes.expand() returns value of type Iterable<T>
.
In this example,
numbers
containing integers.expand()
method with a function that returns the element and the element plus one.void main() {
List<int> numbers = [1, 2, 3];
Iterable<int> expanded = numbers.expand((element) => [element, element + 1]);
print(expanded.toList());
}
[1, 2, 2, 3, 3, 4]
In this example,
words
containing strings.expand()
method with a function that returns the uppercase and lowercase versions of each word.void main() {
List<String> words = ['hello', 'world'];
Iterable<String> expanded = words.expand((word) => [word.toUpperCase(), word.toLowerCase()]);
print(expanded.toList());
}
[HELLO, hello, WORLD, world]
In this example,
uniqueNumbers
containing integers.expand()
method with a function that returns the number and the number multiplied by two.void main() {
Set<int> uniqueNumbers = {1, 2, 3};
Iterable<int> expanded = uniqueNumbers.expand((number) => [number, number * 2]);
print(expanded.toList());
}
[1, 2, 2, 4, 3, 6]
In this Dart tutorial, we learned about expand() method of Runes: the syntax and few working examples with output and detailed explanation for each example.