Dart List firstWhere()
Syntax & Examples


Syntax of List.firstWhere()

The syntax of List.firstWhere() method is:

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

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

Parameters

ParameterOptional/RequiredDescription
testrequireda function that returns true for the desired element
orElseoptionala function that returns a default value if no element is found

Return Type

List.firstWhere() returns value of type E.



✐ Examples

1 Find the first even number in a list

In this example,

  1. We create a list named numbers containing integers.
  2. We use the firstWhere() method with a function that checks for even numbers.
  3. The first even number in numbers is returned.
  4. We print the first even number to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  int firstEven = numbers.firstWhere((element) => element % 2 == 0);
  print('First even number: $firstEven');
}

Output

First even number: 2

2 Find the first word longer than 5 characters in a list

In this example,

  1. We create a list named words containing strings.
  2. We use the firstWhere() method with a function that checks for words longer than 5 characters.
  3. The first word longer than 5 characters in words is returned, or a default message if no such word exists.
  4. We print the result to standard output.

Dart Program

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

Output

Long word: banana

3 Find the first even number in an empty list with a default value

In this example,

  1. We create an empty list named emptyList.
  2. We use the firstWhere() method with a function that checks for even numbers and a default value function.
  3. Since the list is empty, the default value (-1) is returned.
  4. We print the default element to standard output.

Dart Program

void main() {
  List<int> emptyList = [];
  int defaultElement = emptyList.firstWhere((element) => element % 2 == 0, orElse: () => -1);
  print('Default element: $defaultElement');
}

Output

Default element: -1

Summary

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