Dart Set singleWhere()
Syntax & Examples


Set.singleWhere() method

The `singleWhere` method in Dart returns the single element from the set that satisfies the provided test.


Syntax of Set.singleWhere()

The syntax of Set.singleWhere() method is:

 E singleWhere(bool test(E element), { E orElse() }) 

This singleWhere() method of Set returns the single element that satisfies test.

Parameters

ParameterOptional/RequiredDescription
testrequiredThe function used to test elements of the set.
orElseoptionalA function that returns the value to use if the set is empty or if no elements satisfy the test. If not provided, a StateError is thrown.

Return Type

Set.singleWhere() returns value of type E.



✐ Examples

1 Find single integer satisfying condition

In this example,

  1. We create a Set set containing integers.
  2. We use the singleWhere() method with a test function that checks if each element is equal to 3.
  3. We print the single element that satisfies the condition to standard output.

Dart Program

void main() {
  Set<int> set = {1, 2, 3, 4, 5};
  int single = set.singleWhere((element) => element == 3);
  print('Single element: $single');
}

Output

Single element: 3

2 Find single string with length 5 or default

In this example,

  1. We create a Set set containing strings.
  2. We use the singleWhere() method with a test function that checks if the length of each string is 5.
  3. We provide an orElse function to return a default value if no element satisfies the condition.
  4. We print the single element that satisfies the condition or the default value to standard output.

Dart Program

void main() {
  Set<String> set = {'apple', 'banana', 'orange'};
  String single = set.singleWhere((element) => element.length == 5, orElse: () => 'No matching element');
  print('Single element or default: $single');
}

Output

Single element or default: banana

Summary

In this Dart tutorial, we learned about singleWhere() method of Set: the syntax and few working examples with output and detailed explanation for each example.