Dart List toList()
Syntax & Examples
Syntax of toList()
The syntax of List.toList() method is:
List<E> toList({bool growable = true})
This toList() method of List creates a List
containing the elements of this Iterable
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
growable | optional [default value is true] | whether the created list can grow dynamically or not |
Return Type
List.toList() returns value of type List<E>
.
✐ Examples
1 Convert iterable of numbers to list
In this example,
- We create an iterable named
iterable
containing integers. - We call the
toList()
method on the iterable to convert it into a list. - The resulting list contains all elements from the iterable.
- We print the list to standard output.
Dart Program
void main() {
Iterable<int> iterable = [1, 2, 3, 4, 5];
var list = iterable.toList();
print(list);
}
Output
[1, 2, 3, 4, 5]
2 Convert iterable of characters to list
In this example,
- We create an iterable named
iterable
containing characters. - We call the
toList()
method on the iterable to convert it into a list. - The resulting list contains all elements from the iterable.
- We print the list to standard output.
Dart Program
void main() {
Iterable<String> iterable = ['a', 'b', 'c'];
var list = iterable.toList();
print(list);
}
Output
[a, b, c]
3 Convert iterable of strings to list
In this example,
- We create an iterable named
iterable
containing strings. - We call the
toList()
method on the iterable to convert it into a list. - The resulting list contains all elements from the iterable.
- We print the list to standard output.
Dart Program
void main() {
Iterable<String> iterable = ['apple', 'banana', 'cherry'];
var list = iterable.toList();
print(list);
}
Output
[apple, banana, cherry]
Summary
In this Dart tutorial, we learned about toList() method of List: the syntax and few working examples with output and detailed explanation for each example.