Dart program to check if a list contains a specific element or not

Dart program to check if a list contains a specific element or not:

In this post, we will learn how to find if a list contains a specific element or not. Dart list provides one method contains() for that. We can use this method or we can use one loop to check if the element is present in that list.

Method 1: By looping over the elements:

We can use one loop, iterate over the list and compare each element to check if any of these elements equal to the given element.

For example :

main(List<String> args) {
  var myList = [1, 2, 4, 5, 6, 7, 0, 9];
  var itemToFind = 7;

  var found = false;

  for (final item in myList) {
    if (item == itemToFind) {
      found = true;
      break;
    }
  }

  if (found) {
    print("$itemToFind is present in the list");
  } else {
    print("$itemToFind is not present in the list");
  }
}

In this example, we are using one for in loop to iterate through the elements of the list. found is a boolean flag that represents if the given item itemToFind is present in the list myList or not. true indicates that it is present and false indicates not.

Inside the for in loop, if the current iterating item is equal to itemToFind, we are marking found as true and exiting the loop.

For this program, it will print the below output:

7 is present in the list

Method 2: Using any() method:

any can check if a condition satisfies in a list. This method actually uses for in internally. So, it’s complexity is similar to the above example.

Below example is showing how any works:

main(List<String> args) {
  var myList = [1, 2, 4, 5, 6, 7, 0, 9];
  var itemToFind = 7;

  var found =  myList.any((item) => item == itemToFind);

  if (found) {
    print("$itemToFind is present in the list");
  } else {
    print("$itemToFind is not present in the list");
  }
}

Method 3: contains() method:

contains takes one element as its parameter and returns one boolean value if it finds that value in the list or not. If it finds it, then it returns true, else false.

For example:

main(List<String> args) {
  var myList = [1, 2, 4, 5, 6, 7, 0, 9];
  var itemToFind = 7;

  var found =  myList.contains(itemToFind);

  if (found) {
    print("$itemToFind is present in the list");
  } else {
    print("$itemToFind is not present in the list");
  }
}

It prints the same output.

You might also like: