Dart: Converting a List to a Set and vice versa

Updated: March 31, 2023 By: Pennywise Post a comment

In Dart, a list is an indexable collection of objects with a length while a set is a collection of objects where each object can occur only once. This short article shows you how to convert a list into a set and vice versa, turn a set into a list.

Converting a list to a set

The toSet() method helps us do the job. Because of the primitive nature of sets, if our list has duplicate elements, they will be removed, and only one will be kept.

Example:

import 'package:flutter/foundation.dart';

void main() {
  final List list1 = [1, 2, 3, 4, 1, 3, 2];
  final List list2 = ['a', 'b', 'c', 'a', 'c', 'd', 'e'];

  final set1 = list1.toSet();
  final set2 = list2.toSet();

  if (kDebugMode) {
    print(set1);
    print(set2);
  }
}

Output:

{1, 2, 3, 4}
{a, b, c, d, e}

You can see that the results contain curly brackets instead of square brackets. Besides, the number of elements of the sets is less than the number of elements of the corresponding input lists because the duplicates are gone.

Converting a set to a list

You can turn a set into a list by using the toList() method.

Example:

import 'package:flutter/foundation.dart';

void main() {
  final Set<int> set1 = {1, 2, 3};
  final Set<Map<String, dynamic>> set2 = {
    {"name": "John Doe", "age": 99},
    {"name": "Voldermort", "age": 71}
  };

  final list1 = set1.toList();
  final list2 = set2.toList();

  if (kDebugMode) {
    print(list1);
    print(list2);
  }
}

Output:

[1, 2, 3]
flut[{name: John Doe, age: 99}, {name: Voldermort, age: 71}]

Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles