Search code snippets, questions, articles...

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');
}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

The list is empty

In the above code example:

  1. We have defined a list(myList) that will be checked if it is empty or not.
  2. We are using isEmpty to check whether the given list is empty or not.
  3. 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
Was this helpful?
0 Comments