Dart – Check if Set contains Specific Element
To check if specified element is present in a Set in Dart, call contains()
method on this Set and pass the search element as argument to it. Set.contains(element)
method returns true
if the element
is present, or false
if not.
Syntax
The syntax to check if given element
is present in mySet
using contains()
method is
</>
Copy
mySet.contains(element)
Examples
In the following program, we take a Set mySet
with some elements, and check if the element 'banana'
is present in this Set.
main.dart
</>
Copy
void main() {
var mySet = {'apple', 'banana', 'cherry'};
var element = 'banana';
if (mySet.contains(element)) {
print('Given element is present in the set.');
} else {
print('Given element is not present in the set.');
}
}
Output
Given element is present in the set.
Now, let us check if the element 'mango'
, is present in the Set or not.
main.dart
</>
Copy
void main() {
var mySet = {'apple', 'banana', 'cherry'};
var element = 'mango';
if (mySet.contains(element)) {
print('Given element is present in the set.');
} else {
print('Given element is not present in the set.');
}
}
Output
Given element is not present in the set.
Conclusion
In this Dart Tutorial, we learned how to check if a specified element is present a Set in Dart programming, with examples.