Dart List expand()
Syntax & Examples
Syntax of List.expand()
The syntax of List.expand() method is:
Iterable<T> expand<T>(Iterable<T> toElements(E element))
This expand() method of List expands each element of this Iterable
into zero or more elements.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
toElements | required | a function that converts each element into zero or more elements |
Return Type
List.expand() returns value of type Iterable<T>
.
✐ Examples
1 Expand numbers in a list
In this example,
- We create a list named
numbers
containing integers. - We use the
expand()
method with a function that duplicates each element and adds one to it. - The resulting iterable contains the expanded numbers.
- We print the expanded numbers to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3];
Iterable<int> expandedNumbers = numbers.expand((element) => [element, element + 1]);
print('Expanded numbers: $expandedNumbers');
}
Output
Expanded numbers: (1, 2, 2, 3, 3, 4)
2 Expand words in a list
In this example,
- We create a list named
words
containing strings. - We use the
expand()
method with a function that splits each word into individual characters. - The resulting iterable contains the expanded words.
- We print the expanded words to standard output.
Dart Program
void main() {
List<String> words = ['hello', 'world'];
Iterable<String> expandedWords = words.expand((element) => element.split(''));
print('Expanded words: $expandedWords');
}
Output
Expanded words: (h, e, l, l, o, w, o, r, l, d)
3 Expand elements in a set
In this example,
- We create a set named
set
containing integers. - We use the
expand()
method with a function that duplicates each element and multiplies it by two. - The resulting iterable contains the expanded set elements.
- We print the expanded set elements to standard output.
Dart Program
void main() {
Set<int> set = {1, 2, 3};
Iterable<int> expandedSet = set.expand((element) => [element, element * 2]);
print('Expanded set: $expandedSet');
}
Output
Expanded set: (1, 2, 2, 4, 3, 6)
Summary
In this Dart tutorial, we learned about expand() method of List: the syntax and few working examples with output and detailed explanation for each example.