Dart Runes singleWhere()
Syntax & Examples
Runes.singleWhere() method
The `singleWhere` method in Dart returns the single element that satisfies the given predicate, or throws an error if none or more than one element matches the predicate.
Syntax of Runes.singleWhere()
The syntax of Runes.singleWhere() method is:
int singleWhere(bool test(int element), { int orElse() })
This singleWhere() method of Runes returns the single element that satisfies test
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
test | required | A function that takes an integer element as input and returns a boolean value indicating whether the element satisfies the test. |
orElse | optional | A function that returns an integer value to be used if no or more than one element satisfies the test. |
Return Type
Runes.singleWhere() returns value of type int
.
✐ Examples
1 Find character code
In this example,
- We create a sequence of Unicode code points
runes
from the string 'Hello'. - We use the
singleWhere
method with a test function to find the single character code for 'H' (Unicode code point 72). - We then print the character code to standard output.
Dart Program
void main() {
Runes runes = Runes('Hello');
int characterCode = runes.singleWhere((element) => element == 72);
print('Character code: $characterCode');
}
Output
Character code: 72
2 Find digit
In this example,
- We create a sequence of Unicode code points
numbers
from the string '12345'. - We use the
singleWhere
method with a test function to find the single digit '2' (Unicode code point 50). - We then print the digit to standard output.
Dart Program
void main() {
Runes numbers = Runes('12345');
int digit = numbers.singleWhere((element) => element == 50);
print('Digit: $digit');
}
Output
Digit: 50
Summary
In this Dart tutorial, we learned about singleWhere() method of Runes: the syntax and few working examples with output and detailed explanation for each example.