close

Check value in array exists Flutter dart

Check if Dart List contains Element

You can check if a component is available in Dart List. There are numerous approaches to do check the presence of a component in elite.

Arrangement 1: List.contains() is a strategy that acknowledges a component and checks if the component is available in this rundown.

Arrangement 2: Iterate over the components of rundown and check for equity. As and when the component establishes a match, you may break the circle and guarantee for the component to be available in given rundown.

In this instructional exercise, we will experience the above said arrangements with Dart programs.

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

List.contains(element) returns valid if the component is available in this rundown. Else, it returns bogus.

In this Dart program, we will take a rundown of numbers and check if 84 is available in this rundown. We will check for the number 77 moreover.

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 figured out how to check if a component is available in the Dart List utilizing List.contains() or for circle.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment