{

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 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?

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

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

Dart| Flutter How to get File name and extension with example