Dart| Flutter How to: Find Set is Empty or not
This tutorial shows different ways to determine whether or not a set is empty in Dart or Flutter.
- How to test whether a given Set is null or not and whether its length is zero.
- Determine whether the Set is empty or blank.
- Verify that the Set contains Zero elements
A set is one of the data structures to store the collection of elements without duplicates.
You can check another post, How to create an empty Set in flutter
In dart, what is an empty set?
An empty set has no elements and is blank. Dart Set has built-in properties for checking whether a set is empty or not.
length
: returns the total number of elements in a Set. If it returns 0 then the Set is empty.isEmpty
: Checks for an empty Set and returns a boolean value, true indicates that the Set is empty.isNotEmpty
: Checks for a non-empty Set and returns a boolean value. false indicates that the Set is empty.
How to check whether Set is empty or not in Dart Flutter using the isEmpty property in dart
isEmpty
always returns a boolean value true
or false
. - true
: return if the Set is empty. - false
: return if the Set is non-empty.
It is used to check the Set is empty without key and value pairs.
Here is an example program code
void main() {
Set set = {};
print(set.isEmpty); //true
if (set.isEmpty)
print("set is empty");
else {
print("set is not empty");
}
}
Output:
true
set is empty
Set contains empty or not using the isNonEmpty property in the dart
isNonEmpty
always returns the boolean value true or false. - true
: return if the Set is non-empty. - false
: return if the Set is empty.
It checks a Set for non-empty and returns true and false Here is an example code
void main() {
Set set = {};
print(set.isNotEmpty); //true
if (set.isNotEmpty)
print("set is not empty");
else {
print("set is empty");
}
}
Output:
false
set is empty
How to Check an empty Set using the length property in the flutter
The length
property always returns an int
value. If it is ‘zero,’ the Set is empty.
Otherwise, the set is not empty.
It, like the other approaches mentioned above, does not return a boolean value.
It is used in conditional statements such as ‘if’, and the result must be compared to zero again, i.e. (set.length==0).
This approach is recommended to use the size of a Set object.
Here’s an example of a code
void main() {
Set set = {};
print(set.length); //0
if (set.length == 0)
print("set is empty");
else {
print("set is not empty");
}
}
Output:
0
set is empty
Conclusion
Learned multiple approaches to find an empty set or not in dart and flutter.