To check if a specific item is present in a Set in Dart, you can use the contains
method of the Set
class.
In this example,
Set
named numbers
and initialize it with some integer elements.itemToCheck
with the value of the item we want to check for.contains
method of the numbers
set to check if itemToCheck
is present in the set.contains
method returns a boolean value: true
if the item is present, and false
if it is not.void main() {
Set<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int itemToCheck = 5;
bool containsItem = numbers.contains(itemToCheck);
print('Does the set contain $itemToCheck? $containsItem');
}
Does the set contain 5? true
In this example,
Set
named fruits
and initialize it with some string elements.itemToCheck
with the value of the item we want to check for.contains
method of the fruits
set to check if itemToCheck
is present in the set.contains
method returns a boolean value: true
if the item is present, and false
if it is not.void main() {
Set<String> fruits = {'apple', 'banana', 'cherry', 'date', 'fig'};
String itemToCheck = 'cherry';
bool containsItem = fruits.contains(itemToCheck);
print("Does the set contain '$itemToCheck'? $containsItem");
}
Does the set contain 'cherry'? true
In this tutorial, we learned How to check if a Specific Item is present in the Set in Dart language with well detailed examples.