Dart Set firstWhere()
Syntax & Examples


Syntax of Set.firstWhere()

The syntax of Set.firstWhere() method is:

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

This firstWhere() method of Set returns the first element that satisfies the given predicate test.

Parameters

ParameterOptional/RequiredDescription
testrequiredA function that takes an element of the iterable and returns a boolean value.
orElseoptionalA function that returns a default value if no element is found that satisfies the test.

Return Type

Set.firstWhere() returns value of type E.



✐ Examples

1 Finding the first even number

In this example,

  1. We create a List numbers with values [1, 2, 3, 4, 5].
  2. We use the firstWhere() method with a test function that finds the first even number.
  3. We print the result, which is the first even number in the list.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  int firstEven = numbers.firstWhere((element) => element.isEven);
  print(firstEven);
}

Output

2

2 Finding the first long word

In this example,

  1. We create a List words with values ['apple', 'banana', 'cherry'].
  2. We use the firstWhere() method with a test function that finds the first word with length greater than 10.
  3. If no such word is found, we return 'No long word found' using the orElse parameter.
  4. We print the result, which is the first long word or the default message.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry'];
  String longWord = words.firstWhere((element) => element.length > 10, orElse: () => 'No long word found');
  print(longWord);
}

Output

No long word found

Summary

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