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
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 |
Return Type
List.singleWhere() returns value of type E
.
✐ Examples
1 Find element in a list of numbers
In this example,
- We create a list
numbers
containing integers. - We use
singleWhere
to find the element equal to3
innumbers
. - Since
3
is present only once, it is returned as the result. - 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,
- We create a list
characters
containing characters. - We use
singleWhere
to find the element equal to'b'
incharacters
. - Since
'b'
is present only once, it is returned as the result. - 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.