To remove items from a set based on a condition in Dart, you can use the removeWhere method with a predicate function that defines the condition.
In this example,
numberSet
containing integer values 1
, 2
, 3
, 4
, and 5
.removeWhere
method with a predicate function that checks for even numbers to remove them from the set.numberSet
to see the removed items.void main() {
Set<int> numberSet = {1, 2, 3, 4, 5};
numberSet.removeWhere((num) => num % 2 == 0);
print(numberSet);
}
{1, 3, 5}
In this example,
stringSet
containing string values 'apple'
, 'banana'
, 'cherry'
, 'date'
, and 'grape'
.removeWhere
method with a predicate function that checks for string length less than 6 characters to remove them from the set.stringSet
to see the removed items.void main() {
Set<String> stringSet = {'apple', 'banana', 'cherry', 'date', 'grape'};
stringSet.removeWhere((str) => str.length < 6);
print(stringSet);
}
{'banana', 'cherry'}
In this tutorial, we learned How to Remove Items from Set based on a Condition in Dart language with well detailed examples.