Dart – Check if List is Empty

An empty list means that there are no elements in the list.

There are many ways in which you can check this.

The length property of an empty list returns zero.

Or you can use built-in property List.isEmpty. List.isEmpty returns true if the list is empty and false if it is not.

We have one more built-in property to check if the list is empty or not. But this one checks if the List is not emtpy. The property is List.isNotEmpty.

In this tutorial, we go through these three ways of finding if a list is empty or not.

Check if Dart List is Empty using Length property

In the following dart program, we have written a function checkList() where it receives the list as argument. It checks the length and based on the return value, it decides if the list is empty or not.

In the main function, we shall call function checkList() for an empty list and a non-empty list.

Dart Program

void checkList(var myList){
	//length of empty list is zero
	if(myList.length == 0){
		print("List "+myList.toString()+" is empty");
	} else{
		print("List "+myList.toString()+" is not empty");
	}
}

void main(){
	var list1 = [];
	checkList(list1);
	
	var list2 = [24, 56, 84];
	checkList(list2);
}

Output

D:\tutorialkart\workspace\dart_tutorial>dart example.dart
List [] is empty
List [24, 56, 84] is not empty

The result is obvious. List [] is empty and List [24, 56, 84] is not empty.

Check if Dart List is Empty using isEmpty property

In the following Dart Program, we shall use isEmpty property of List class and decide if the list is empty or not.

Dart Program

void checkList(var myList){
	//isEmpty returns true if list is emtpy
	if(myList.isEmpty){
		print("List "+myList.toString()+" is empty");
	} else{
		print("List "+myList.toString()+" is not empty");
	}
}

void main(){
	var list1 = [];
	checkList(list1);
	
	var list2 = [24, 56, 84];
	checkList(list2);
}

Output

D:\tutorialkart\workspace\dart_tutorial>dart example.dart
List [] is empty
List [24, 56, 84] is not empty

Check if Dart List is Empty using isNotEmpty property

This is same as that of the previous example, but we are using isNotEmpty property of List class.

Dart Program

void checkList(var myList){
	//isEmpty returns true if list is emtpy
	if(myList.isNotEmpty){
		print("List "+myList.toString()+" is not empty");
	} else{
		print("List "+myList.toString()+" is empty");
	}
}

void main(){
	var list1 = [];
	checkList(list1);
	
	var list2 = [24, 56, 84];
	checkList(list2);
}

Output

D:\tutorialkart\workspace\dart_tutorial>dart example.dart
List [] is empty
List [24, 56, 84] is not empty

Conclusion

In this Dart Tutorial, we learned some of the ways to check if a list is empty of not in Dart using some built-in functions.