Dart List singleWhere()
Syntax & Examples


Syntax of List.singleWhere()

The syntax of List.singleWhere() method is:

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

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

Parameters

ParameterOptional/RequiredDescription
testrequiredthe test function that an element must satisfy
orElseoptionala function that provides a default value if no element is found

Return Type

List.singleWhere() returns value of type E.



✐ Examples

1 Find element in a list of numbers

In this example,

  1. We create a list numbers containing integers.
  2. We use singleWhere to find the element equal to 3 in numbers.
  3. Since 3 is present only once, it is returned as the result.
  4. We print the result to standard output.

Dart Program

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

Output

3

2 Find element in a list of characters

In this example,

  1. We create a list characters containing characters.
  2. We use singleWhere to find the element equal to 'b' in characters.
  3. Since 'b' is present only once, it is returned as the result.
  4. We print the result to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd', 'e'];
  String result = characters.singleWhere((element) => element == 'b');
  print(result);
}

Output

b

Summary

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