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:
-
The first line of the code specifies the
main()
method. This is the entry point of every Dart program. -
Inside the
main()
method, we initialize a List of Strings called ‘stringList’ that contains four different programming languages: Dart, Python, Java, and JavaScript. -
We then define a String variable ‘searchString’, and assign it the value ‘Python’ - the element we’re looking to find in the list.
-
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. -
With an
if
statement, we check the result of thecontains()
method call. If it is ‘true’, the message ‘$searchString is present in the list.’ is printed on the console. However, ifcontains()
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.