Dart Set contains()
Syntax & Examples


Syntax of Set.contains()

The syntax of Set.contains() method is:

 bool contains(Object value) 

This contains() method of Set returns true if value is in the set.

Parameters

ParameterOptional/RequiredDescription
valuerequiredThe value to check if it exists in the Set.

Return Type

Set.contains() returns value of type bool.



✐ Examples

1 Checking integer in Set

In this example,

  1. We create a Set numSet with values {1, 2, 3}.
  2. We set checkValue to 2.
  3. We use the contains() method to check if numSet contains checkValue.
  4. We print the result indicating whether numSet contains checkValue.

Dart Program

void main() {
  Set<int> numSet = {1, 2, 3};
  int checkValue = 2;
  bool result = numSet.contains(checkValue);
  print('Contains $checkValue: $result');
}

Output

Contains 2: true

2 Checking integer in Set which is not present

In this example,

  1. We create a Set numSet with values {1, 2, 3}.
  2. We set checkValue to 5.
  3. We use the contains() method to check if numSet contains checkValue.
  4. We print the result indicating whether numSet contains checkValue.

Dart Program

void main() {
  Set<int> numSet = {1, 2, 3};
  int checkValue = 5;
  bool result = numSet.contains(checkValue);
  print('Contains $checkValue: $result');
}

Output

Contains 5: false

3 Checking string in Set

In this example,

  1. We create a Set wordSet with values {'apple', 'banana', 'cherry'}.
  2. We set checkWord to 'banana'.
  3. We use the contains() method to check if wordSet contains checkWord.
  4. We print the result indicating whether wordSet contains checkWord.

Dart Program

void main() {
  Set<String> wordSet = {'apple', 'banana', 'cherry'};
  String checkWord = 'banana';
  bool result = wordSet.contains(checkWord);
  print('Contains $checkWord: $result');
}

Output

Contains banana: true

Summary

In this Dart tutorial, we learned about contains() method of Set: the syntax and few working examples with output and detailed explanation for each example.