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
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | the test function that an element must satisfy |
orElse | optional | a function that provides a default value if no element is found |
List.singleWhere() returns value of type E
.
In this example,
numbers
containing integers.singleWhere
to find the element equal to 3
in numbers
.3
is present only once, it is returned as the result.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int result = numbers.singleWhere((element) => element == 3);
print(result);
}
3
In this example,
characters
containing characters.singleWhere
to find the element equal to 'b'
in characters
.'b'
is present only once, it is returned as the result.void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
String result = characters.singleWhere((element) => element == 'b');
print(result);
}
b
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.