{

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


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

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 convert Double to Integer or Integer to double in Dart| Flutter By Example

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not