Dart – Check if List is Empty

An empty List means, no elements in the List. There are many ways in which we can check if the given List is empty or not. They are

  • length property of an empty List returns zero.
  • List.isEmpty property returns true if the List is empty, or false if it is not.
  • List.isNotEmpty property returns false if the List is empty, or true if it is not.

In this tutorial, we go through each of these ways of checking if given Set is empty or not.

Check if List is Empty using Length property

In the following example, we have taken an empty List myList, and we shall programmatically check if this List is empty using List.length property.

If the List is empty, then the length property on this List returns 0.

Dart Program

void main() {
  var myList = [];
  if (myList.length == 0) {
    print('List is empty.');
  } else {
    print('List is not empty.');
  }
}

Output

List is empty.

Check if 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 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.