Dart – Check if Set is Empty

An empty Set means, no elements in the Set. There are many ways in which we can check if the given Set is empty or not. They are

  • length property of an empty Set returns zero.
  • Set.isEmpty property returns true if the Set is empty, or false if it is not.
  • Set.isNotEmpty property returns false if the Set is empty, or true if it is not.

In this tutorial, we go through each of these ways of checking if given Set is empty or not.

Check if Set is empty using length property

In the following example, we have taken an empty Set mySet, and we shall programmatically check if this Set is empty using Set.length property.

If the Set is empty, then the length property on this Set returns 0.

main.dart

void main() {
  var mySet = {};
  if (mySet.length == 0) {
    print('Set is empty.');
  } else {
    print('Set is not empty.');
  }
}

Output

Set is empty.
ADVERTISEMENT

Check if Set is empty using isEmpty property

In the following example, we have taken an empty Set mySet, and we shall programmatically check if this Set is empty using Set.isEmpty property.

If the Set is empty, then the isEmpty property returns true, else isEmpty returns false.

main.dart

void main() {
  var mySet = {};
  if (mySet.isEmpty) {
    print('Set is empty.');
  } else {
    print('Set is not empty.');
  }
}

Output

Set is empty.

Check if Set is empty using isNotEmpty property

In the following example, we have taken an empty Set mySet, and we shall programmatically check if this Set is empty using Set.isNotEmpty property.

If the Set is empty, then the isNotEmpty property returns false, else isNotEmpty returns true.

main.dart

void main() {
  var mySet = {};
  if (mySet.isNotEmpty) {
    print('Set is not empty.');
  } else {
    print('Set is empty.');
  }
}

Output

Set is empty.

Conclusion

In this Dart Tutorial, we learned some of the ways to check if a Set is empty of not in Dart, with examples.