Dart Set retainWhere()
Syntax & Examples
Set.retainWhere() method
The `retainWhere` method in Dart removes all elements from the set that fail to satisfy a given test.
Syntax of Set.retainWhere()
The syntax of Set.retainWhere() method is:
 void retainWhere(bool test(E element)) This retainWhere() method of Set removes all elements of this set that fail to satisfy test.
Parameters
| Parameter | Optional/Required | Description | 
|---|---|---|
test | required | A function that takes an element of the set as input and returns a boolean value. If the return value is false, the element is removed from the set. | 
Return Type
Set.retainWhere() returns value of type  void.
✐ Examples
1 Retain even numbers in set
In this example,
- We create a Set 
setcontaining integers. - We use the 
retainWhere()method with a test function that retains only even numbers. - We print the resulting Set to standard output.
 
Dart Program
void main() {
  Set<int> set = {1, 2, 3, 4};
  set.retainWhere((element) => element % 2 == 0);
  print('Set after retaining even numbers: $set');
}Output
Set after retaining even numbers: {2, 4}2 Retain strings with length greater than 5 in set
In this example,
- We create a Set 
setcontaining strings. - We use the 
retainWhere()method with a test function that retains only strings with a length greater than 5. - We print the resulting Set to standard output.
 
Dart Program
void main() {
  Set<String> set = {'apple', 'banana', 'orange', 'grape'};
  set.retainWhere((element) => element.length > 5);
  print('Set after retaining strings with length greater than 5: $set');
}Output
Set after retaining strings with length greater than 5: {banana, orange}Summary
In this Dart tutorial, we learned about retainWhere() method of Set: the syntax and few working examples with output and detailed explanation for each example.