How to convert List to Set or vice-versa in Dart| Flutter By Example

This tutorial shows multiple ways to convert List to Set in Dart or flutter programming.

The List is a dynamic collection of objects in Dart, elements are inserted in insertion order and allow duplicate objects. The Set is a data structure to store a collection of elements and does not allow duplicates.

Both are different types in Dart or Flutter, and We have to write code to convert from one type into another.

How to convert List to Set in Dart or Flutter programming

spread operator(...) is used to spread the values and assign them to Set Literal syntax.

Here is an example program

main() {
  List wordsList = ['one', 'two', 'three'];
  print(wordsList); //[one, two, three]

  print(wordsList.runtimeType); //JSArray<dynamic>

  var wordsSet = {...wordsList};
  print(wordsSet); //{one, two, three}
  print(wordsSet.runtimeType); //_LinkedHashSet<dynamic>
  print(wordsSet is Set); //true
}

Output:

[one, two, three]
JSArray<dynamic>
{one, two, three}
_LinkedHashSet<dynamic>
true

How to convert Set to List in Dart or Flutter programming?

The Set.toList() method is used to convert Set to List

Here is an example program to convert Set into separate lists

main() {
  Set<String> words = {'one', 'two', 'three'};
  List<String> lists = words.toList();

  print(words.runtimeType); //_LinkedHashSet<String>

  print(lists.runtimeType); //JSArray<String>
}

Conclusion

Learn How to Convert List to Set or Set to List in Dart or flutter programming.