Dart Runes firstWhere()
Syntax & Examples

Runes.firstWhere() method

The `firstWhere` method in Dart returns the first element that satisfies the given predicate.


Syntax of Runes.firstWhere()

The syntax of Runes.firstWhere() method is:

 int firstWhere(bool test(int element), { int orElse() }) 

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

Parameters

ParameterOptional/RequiredDescription
testrequiredA function that takes an integer element as input and returns a boolean value indicating whether the element satisfies the test.
orElseoptionalA function that returns an integer value to be used if no element satisfies the test.

Return Type

Runes.firstWhere() returns value of type int.



✐ Examples

1 Find first ASCII character

In this example,

  1. We create a sequence of Unicode code points runes from the string 'Hello'.
  2. We use the firstWhere method with a test function to find the first ASCII character.
  3. We then print the result to standard output.

Dart Program

void main() {
  Runes runes = Runes('Hello');
  int firstAscii = runes.firstWhere((element) => element >= 65 && element <= 90);
  print('First ASCII character: $firstAscii');
}

Output

First ASCII character: 72

2 Find first emoji

In this example,

  1. We create a sequence of Unicode code points emojis from the string '👋🏽🚀🌟'.
  2. We use the firstWhere method with a test function to find the first emoji character.
  3. We then print the result to standard output.

Dart Program

void main() {
  Runes emojis = Runes('👋🏽🚀🌟');
  int firstEmoji = emojis.firstWhere((element) => element >= 128000);
  print('First emoji: $firstEmoji');
}

Output

First emoji: 128075

3 Find first digit

In this example,

  1. We create a sequence of Unicode code points numbers from the string '12345'.
  2. We use the firstWhere method with a test function to find the first digit character.
  3. We then print the result to standard output.

Dart Program

void main() {
  Runes numbers = Runes('12345');
  int firstDigit = numbers.firstWhere((element) => element >= 48 && element <= 57);
  print('First digit: $firstDigit');
}

Output

First digit: 49

Summary

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