{

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. Convert List to Set or Set to List in Dart and flutter

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

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

How to convert List to Set in Dart or Flutter programming

spread operator(...) 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?

Set.toList() method 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example