What is the list.toSet() method in Dart?

A list is a collection of elements having the same data types. It may contain a repetition of elements. To remove them, we can convert the list to a set type.

A set is a collection of elements of the same types as a list but allows one element only once. In dart, we can convert the list to a set using the toSet() method.

Syntax

The syntax of the toSet() method is as follows:

list.toSet()

It takes no parameters. It returns a set that does not have any repetition of elements.

Example

The following code will demonstrate the use of the toSet() method.

import 'dart:convert';
void main() {
final planets = <String> {'Mercury', 'Mercury', 'Venus','Mars','Mars','Mars', 'Earth', 'Pluto'};
final valueSet = planets.toSet();
print(valueSet);
}

Explanation

  • Line 4: We declare a list named planets of type string. The list has some planets’ names, and we can see that there are some repetitions.

  • Line 5: We call the toSet() method of the planets and store the result in valueSet.

  • Line 8: Prints the result set from the toSet() method on the console.

Note: We need to overload the operator when working with custom objects.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved