Generic Collections- Set & Map

In this lesson, you will learn to use generics for two more Dart's collections: Set and Map.

Let’s check out the type safe implementations for two of the Dart’s collection literals: Set & Map.

Set

In a Set collection, each object can only occur once.

Creating Set

A set theSet of the String data type is constructed using the parameterized constructor Set<String>.from({"1"}).

Set<String> theSet = Set<String>.from({"1"});

Same data type item

Two more items of the same type String are added to the set theSet, iterating over the set theSet, and printing all items in the set.

void main() {
  Set<String> theSet = Set<String>.from({"1"});
  theSet.add("2");
  theSet.add("3");

  print("Printing items in Dart Set");
  //iterate over set and print all items
  for (String item in theSet) {
    print(item);
  }
}

Output:

Printing items in Dart Set
1
2
3

Different data type item

Adding a different data type int will throw a compile-time error.

void main() {
  Set<String> theSet = Set<String>.from({"1"});

  //Adding int data type will throw compile time error
  theSet.add(3);
}

Output:

The compile-time error is due to adding int data instead of String data.

main.dart:7:14: Error: The argument type 'int' can't be assigned to the parameter type 'String'.
  theSet.add(3);

Get hands-on with 1200+ tech skills courses.