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
| Parameter | Optional/Required | Description |
|---|---|---|
value | required | The 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,
- We create a Set
numSetwith values {1, 2, 3}. - We set
checkValueto 2. - We use the
contains()method to check ifnumSetcontainscheckValue. - We print the result indicating whether
numSetcontainscheckValue.
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,
- We create a Set
numSetwith values {1, 2, 3}. - We set
checkValueto 5. - We use the
contains()method to check ifnumSetcontainscheckValue. - We print the result indicating whether
numSetcontainscheckValue.
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,
- We create a Set
wordSetwith values {'apple', 'banana', 'cherry'}. - We set
checkWordto 'banana'. - We use the
contains()method to check ifwordSetcontainscheckWord. - We print the result indicating whether
wordSetcontainscheckWord.
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.