Dart List contains()
Syntax & Examples
Syntax of List.contains()
The syntax of List.contains() method is:
bool contains(Object? element) This contains() method of List whether the collection contains an element equal to element.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
element | required | the element to check for in the collection |
Return Type
List.contains() returns value of type bool.
✐ Examples
1 Check if list contains the number 3
In this example,
- We create a list named
numberscontaining the numbers1, 2, 3, 4, 5. - We then use the
contains()method to check ifnumberscontains the number3. - The result, indicating whether
3is contained innumbers, is printed to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
bool containsThree = numbers.contains(3);
print('List contains 3: $containsThree'); // Output: List contains 3: true
}Output
List contains 3: true
2 Check if list contains the character 'd'
In this example,
- We create a list named
characterscontaining the characters'a', 'b', 'c', 'd'. - We then use the
contains()method to check ifcharacterscontains the character'd'. - The result, indicating whether
'd'is contained incharacters, is printed to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c', 'd'];
bool containsD = characters.contains('d');
print('List contains \'d\': $containsD'); // Output: List contains 'd': true
}Output
List contains 'd': true
3 Check if list contains the string 'pear'
In this example,
- We create a list named
fruitscontaining the strings'apple', 'banana', 'orange'. - We then use the
contains()method to check iffruitscontains the string'pear'. - The result, indicating whether
'pear'is contained infruits, is printed to standard output.
Dart Program
void main() {
List<String> fruits = ['apple', 'banana', 'orange'];
bool containsPear = fruits.contains('pear');
print('List contains \'pear\': $containsPear'); // Output: List contains 'pear': false
}Output
List contains 'pear': false
Summary
In this Dart tutorial, we learned about contains() method of List: the syntax and few working examples with output and detailed explanation for each example.