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.
Parameter | Optional/Required | Description |
---|---|---|
toElements | required | a function that converts each element into zero or more elements |
List.expand() returns value of type Iterable<T>
.
In this example,
numbers
containing integers.expand()
method with a function that duplicates each element and adds one to it.void main() {
List<int> numbers = [1, 2, 3];
Iterable<int> expandedNumbers = numbers.expand((element) => [element, element + 1]);
print('Expanded numbers: $expandedNumbers');
}
Expanded numbers: (1, 2, 2, 3, 3, 4)
In this example,
words
containing strings.expand()
method with a function that splits each word into individual characters.void main() {
List<String> words = ['hello', 'world'];
Iterable<String> expandedWords = words.expand((element) => element.split(''));
print('Expanded words: $expandedWords');
}
Expanded words: (h, e, l, l, o, w, o, r, l, d)
In this example,
set
containing integers.expand()
method with a function that duplicates each element and multiplies it by two.void main() {
Set<int> set = {1, 2, 3};
Iterable<int> expandedSet = set.expand((element) => [element, element * 2]);
print('Expanded set: $expandedSet');
}
Expanded set: (1, 2, 2, 4, 3, 6)
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.