Check if Dart List contains Element

You can check if an element is present in Dart List. There are many ways to do check the presence of an element in a list.

Solution 1: List.contains() is an method that accepts an element and checks if the element is present in this list.

Solution 2: Iterate over the elements of list and check for equality. As and when the element founds a match, you may break the loop and claim for the element to be present in given list.

In this tutorial, we will go through the above said solutions with Dart programs.

Check if Dart List contains Element using List.contains()

List.contains(element) returns true if the element is present in this list. Else, it returns false.

In this Dart program, we will take a list of numbers and check if 84 is present in this list. We shall check for the number 77 also.

Dart Program

void main(){
	var myList = [24, 56, 84, 92];
	
	var element = 84;
	
	if(myList.contains(element)){
		print('$element is present in the list $myList');
	} else {
		print('$element is not present in the list $myList');
	}
	
	element = 77;
	
	if(myList.contains(element)){
		print('$element is present in the list $myList');
	} else {
		print('$element is not present in the list $myList');
	}
}

Output

84 is present in the list [24, 56, 84, 92]
77 is not present in the list [24, 56, 84, 92]

As 84 is present in the list, myList.contains(84) returns true.

As 77 is not present in the list, myList.contains(77) returns true.

Check if Dart List contains Element using For Loop and identical() method

This is a very primitive method of checking if the element is present in the list.

Dart Program

void main(){
	var myList = [24, 56, "hello", "dart"];
	
	var element = "hello";
	
	var present = false;
	for(var i=0;i<myList.length;i++) {
		// you may have to check the equality operator
		if(element == myList[i]) {
			present=true;
			break;
		}
	}
	
	if(present){
		print('$element is present in the list $myList');
	} else {
		print('$element is not present in the list $myList');
	}
}

Output

hello is present in the list [24, 56, hello, dart]

Solution 1 is preferred over Solution 2. Solution 2 is only for understanding that there is another way to check if element is present in the list.

Conclusion

In this Dart Tutorial, we learned how to check if an element is present in the Dart List using List.contains() or for loop.