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

ParameterOptional/RequiredDescription
growableoptionalA 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.
growableoptionalA 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,

  1. We create a Set set containing integers.
  2. We use the toList() method without specifying the growable flag, which defaults to true, to create a growable list from the set.
  3. 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,

  1. We create a Set set containing strings.
  2. We use the toList() method with the growable flag set to false to create a fixed-size list from the set.
  3. 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.