Dart Set toList()
Syntax & Examples
Set.toList() method
The `toList` method in Dart creates a List containing all the elements of the set.
Syntax of Set.toList()
The syntax of Set.toList() method is:
List<E> toList({bool growable: true })
This toList() method of Set creates a List containing the elements of this Iterable.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
growable | optional | A boolean flag indicating whether the created list is allowed to grow dynamically. If true, the list is allowed to grow. If false, the list has a fixed size. |
growable | optional | A boolean flag indicating whether the created list is allowed to grow dynamically. If true, the list is allowed to grow. If false, the list has a fixed size. |
Return Type
Set.toList() returns value of type List<E>
.
✐ Examples
1 Convert set to growable list
In this example,
- We create a Set
set
containing integers. - We use the
toList()
method without specifying the growable flag, which defaults to true, to create a growable list from the set. - We print the created list to standard output.
Dart Program
void main() {
Set<int> set = {1, 2, 3, 4, 5};
List<int> list = set.toList();
print('List from set: $list');
}
Output
List from set: [1, 2, 3, 4, 5]
2 Convert set to fixed-size list
In this example,
- We create a Set
set
containing strings. - We use the
toList()
method with the growable flag set to false to create a fixed-size list from the set. - We print the created list to standard output.
Dart Program
void main() {
Set<String> set = {'apple', 'banana', 'orange'};
List<String> list = set.toList(growable: false);
print('List from set: $list');
}
Output
List from set: [apple, banana, orange]
Summary
In this Dart tutorial, we learned about toList() method of Set: the syntax and few working examples with output and detailed explanation for each example.