Check if list is empty in Flutter/Dart
In Dart and Flutter, checking if a list is empty is a common operation. There are a few different ways to do this, but the most common is to use the isEmpty method. This method will return true if the list is empty, and false if the list is not empty.
List myList = [];
if(myList.isEmpty) {
print('The list is empty');
}
Output
The list is empty
In the above code example:
- We have defined a list(myList) that will be checked if it is empty or not.
- We are using isEmpty to check whether the given list is empty or not.
- Printing "The list is empty" if the above process returns true.
Solution 1: Using List.isEmpty in Dart
List.isEmpty is a quick and easy way to check if a list is empty in Flutter. If the list is empty, it will return true, otherwise, it will return false. This is a handy tool to use when checking for data before performing an action on it.
Syntax
List.isEmpty
Code example
List myList = ['John', 'Sandy', 'Truce'];
if(myList.isEmpty) {
print("List is empty");
} else {
print("List is not empty");
}
Output
List is not empty
The code above is a simple example of how to check if a list is empty or not. If the list is empty, the code will print "List is empty". If the list is not empty, the code will print "List is not empty".
Solution 2: Using List.length to check if the list is empty or not
We can also use List.length in Dart to check if a list is empty. This will return 0 if the list is empty. We can understand it using the below code example.
List myList = [];
if(myList.length == 0) {
print('The list is empty');
}
Output
The list is empty
- Check if a String is empty or null in Dart / Flutter
- Remove empty and falsey values from a List in Dart/Flutter
- Remove empty lists from a list of lists and flatten it using Dart
- Reverse a list in Flutter or Dart
- Sort a list in ascending and descending order Dart or Flutter
- Delete item from a List in Flutter [Dart]
- Loop through a List in Flutter [Dart]