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
numSet
with values {1, 2, 3}. - We set
checkValue
to 2. - We use the
contains()
method to check ifnumSet
containscheckValue
. - We print the result indicating whether
numSet
containscheckValue
.
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
numSet
with values {1, 2, 3}. - We set
checkValue
to 5. - We use the
contains()
method to check ifnumSet
containscheckValue
. - We print the result indicating whether
numSet
containscheckValue
.
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
wordSet
with values {'apple', 'banana', 'cherry'}. - We set
checkWord
to 'banana'. - We use the
contains()
method to check ifwordSet
containscheckWord
. - We print the result indicating whether
wordSet
containscheckWord
.
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.