Dart Runes expand()
Syntax & Examples
Runes.expand() method
The `expand` method in Dart expands each element of the Iterable into zero or more elements.
Syntax of Runes.expand()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
f | required | A function that takes an element of the Iterable and returns an Iterable. |
Return Type
Runes.expand() returns value of type Iterable<T>
.
✐ Examples
1 Expanding elements in a list of numbers
In this example,
- We create a list
numbers
containing integers. - We use the
expand()
method with a function that returns the element and the element plus one. - We convert the expanded iterable to a list and print it to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3];
Iterable<int> expanded = numbers.expand((element) => [element, element + 1]);
print(expanded.toList());
}
Output
[1, 2, 2, 3, 3, 4]
2 Expanding elements in a list of strings
In this example,
- We create a list
words
containing strings. - We use the
expand()
method with a function that returns the uppercase and lowercase versions of each word. - We convert the expanded iterable to a list and print it to standard output.
Dart Program
void main() {
List<String> words = ['hello', 'world'];
Iterable<String> expanded = words.expand((word) => [word.toUpperCase(), word.toLowerCase()]);
print(expanded.toList());
}
Output
[HELLO, hello, WORLD, world]
3 Expanding elements in a set of numbers
In this example,
- We create a set
uniqueNumbers
containing integers. - We use the
expand()
method with a function that returns the number and the number multiplied by two. - We convert the expanded iterable to a list and print it to standard output.
Dart Program
void main() {
Set<int> uniqueNumbers = {1, 2, 3};
Iterable<int> expanded = uniqueNumbers.expand((number) => [number, number * 2]);
print(expanded.toList());
}
Output
[1, 2, 2, 4, 3, 6]
Summary
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.