Dart| Flutter How to: Create an Empty Set

This tutorial shows multiple ways to create an empty Set in Dart or Flutter

An empty Set is a Set data structure that contains no elements, and a Set has a length of zero.

In Flutter, an API or service method may return an empty set instead of a null to improve null safety handling.

How to create an Empty Set in Flutter or dart?

An empty Set can be created in multiple ways.

  • using type and brackets

Normally, a Variable of type can be created using type and brackets() and optional new keyword in dart.

Set also can be created with a new keyword

void main() {
  Set set = Set();
  print(set.length); //0
  print(set.runtimeType); //_LinkedHashSet<dynamic>
}

or you can use the new keyword to create a variable for the set

void main() {
  Set set = new Set();
  print(set.length); //0
  print(set.runtimeType); //_LinkedHashSet<dynamic>
}

The above codes create an empty set and return Set.length as zero(0)

It is an empty set without type safety and the default type is Set<dynamic>.

How do you create a typed Set?

void main() {
  Set<String> set = new Set<String>();
  print(set.length); //0
  print(set.runtimeType); //_LinkedHashSet<String>

  Set<String> set1 =  Set<String>();
  print(set1.length); //0
  print(set1.runtimeType); //_LinkedHashSet<String>
}

  • using empty literal syntax

Create a variable and assign the with empty literal using {} syntax.

void main() {
  Set set = {};
  print(set.length); //0
  print(set.runtimeType); //_LinkedHashSet<String>
}

How to create a typed version of the empty literal syntax? This creates an empty array typed set without elements.

void main() {
  Set<String> set = <String>{};
  print(set.length); //0
  print(set.runtimeType); //_LinkedHashSet<String>
}

or you can also use empty literal without type, but the variable type is typed.

void main() {
  Set<String> set = {};
  print(set.length); //0
  print(set.runtimeType); //_LinkedHashSet<String>
}

How to Create an Empty Set of objects in a flutter

The fourth way is, Create an Empty Object Set

Here is an example code for multiple ways to create a Set of objects create a class of employees and create a Set of the empty object using var emps = <Employee>{};

class Employee {
  final int id;
  final String name;
  final int salary;
  final DateTime joinDate;

  Employee(this.id, this.name, this.salary, this.joinDate);
}

void main() {
  Set<Employee> emps1 = new Set<Employee>();
  print(emps1.length); //0
  print(emps1.runtimeType); //_LinkedHashSet<Employee>

  Set<Employee> emps2 = <Employee>{};
  print(emps2.length); //0
  print(emps2.runtimeType); //_LinkedHashSet<Employee>

  Set<Employee> emps3 = {};
  print(emps3.length); //0
  print(emps3.runtimeType); //_LinkedHashSet<Employee>
}

Conclusion

This tutorial talks about multiple ways to create an empty Set typed version of objects.