Dart| Flutter How to: Check List is empty or not Example
This tutorial shows multiple ways how to find if the list is empty or not in Dart or Flutter.
This post talks about the below things.
- How to check if a given list length is zero
- Find list is empty or blank.
- Check List contains nil elements
What is an empty list in dart?
An empty list is a list with no elements and is blank.
You can check another post, create an empty list in flutter
Dart List provides inbuilt methods and properties to check empty or blank list
length
: returns a count of elements in a List. if returns 0, the list is empty.isEmpty
: Checks empty list and returns a boolean value, true means Empty list.isNotEmpty
: Checks non-empty list and returns a boolean value, false means Empty list.
How to check whether List 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 list is empty. - false
: return if the list is non-empty.
This is used to check if the list is empty.
Here is an example program code
void main() {
var numbers = List.empty();
print(numbers.isEmpty); //true
if (numbers.isEmpty)
print("list is empty");
else {
print("list is not empty");
}
}
Output:
true
list is empty
Check if the list is non-empty using the isNonEmpty property in the dart
isNonEmpty
always returns the boolean value true or false. - true
: return if the list is non-empty. - false
: return if the list is empty.
It is used to checklist is empty or non-empty.
Here is an example code
void main() {
var numbers = List.empty();
print(numbers.isNotEmpty); //false
if (numbers.isNotEmpty)
print("list is empty");
else {
print("list is not empty");
}
}
Output:
false
the list is not empty
How to Check an empty list using the length property in the flutter
The length
property always returns the int
number. if it is zero
, an empty list. else, not an empty list.
Like other approaches above, It does not return a boolean value. It uses in condition statements such as if
, you have to again compare the result with zero i.e (numbers.length==0).
This approach is recommended to use the size of a List object.
Here is an example code
void main() {
var numbers = List.empty();
print(numbers.length); //0
if (numbers.length==0)
print("list is empty");
else {
print("list is not empty");
}
}
Output:
0
list is empty
Conclusion
Learned multiple approaches to finding an empty list or not in dart and flutter.