Dart Tutorials

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

ParameterOptional/RequiredDescription
elementrequiredthe 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,

  1. We create a list named numbers containing the numbers 1, 2, 3, 4, 5.
  2. We then use the contains() method to check if numbers contains the number 3.
  3. The result, indicating whether 3 is contained in numbers, 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,

  1. We create a list named characters containing the characters 'a', 'b', 'c', 'd'.
  2. We then use the contains() method to check if characters contains the character 'd'.
  3. The result, indicating whether 'd' is contained in characters, 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,

  1. We create a list named fruits containing the strings 'apple', 'banana', 'orange'.
  2. We then use the contains() method to check if fruits contains the string 'pear'.
  3. The result, indicating whether 'pear' is contained in fruits, 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.