OneBite.Dev - Coding blog in a bite size

Search For A Specific Element In An Array In Dart

Code snippet for how to Search For A Specific Element In An Array In Dart with sample and detail explanation

Searching for a specific element in an array (also known as a List in Dart) is a common operation that programmers come across in their everyday coding practices. In this article, we’ll take a look at an easy and efficient way to perform this task using Dart programming language.

Dart Code to Search For A Specific Element In An Array

void main() { 
   List<String> stringList = ['Dart', 'Python', 'Java', 'JavaScript'];
   String searchString = 'Python';
   
   if (stringList.contains(searchString)) {
      print('$searchString is present in the list.');
   } else {
      print('$searchString is not present in the list.');
   }
}

Code Explanation for Searching For A Specific Element In An Array In Dart

In the Dart program above, we’re searching for a specific element in a List of Strings. Let’s break down how it works:

  1. The first line of the code specifies the main() method. This is the entry point of every Dart program.

  2. Inside the main() method, we initialize a List of Strings called ‘stringList’ that contains four different programming languages: Dart, Python, Java, and JavaScript.

  3. We then define a String variable ‘searchString’, and assign it the value ‘Python’ - the element we’re looking to find in the list.

  4. Then, we use the contains() method provided by Dart to check if the ‘stringList’ includes the ‘searchString’. This method will return a Boolean value - ‘true’ if the list contains the specified element, and ‘false’ if it doesn’t.

  5. With an if statement, we check the result of the contains() method call. If it is ‘true’, the message ‘$searchString is present in the list.’ is printed on the console. However, if contains() returns ‘false’, the message ‘$searchString is not present in the list.’ gets printed.

By using this technique, you can search for any specific element in a Dart Array or List. This method performs a linear search, which means it checks each element of the list one by one. Therefore, the time complexity of this operation is O(n) where ‘n’ is the length of the list.

dart