firstWhere method

  1. @override
I firstWhere(
  1. bool test(
    1. I
    ), {
  2. I orElse()?,
})
override

The first element that satisfies the given predicate test.

Iterates through elements and returns the first to satisfy test.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.firstWhere((element) => element < 5); // 1
result = numbers.firstWhere((element) => element > 5); // 6
result =
    numbers.firstWhere((element) => element > 10, orElse: () => -1); // -1

If no element satisfies test, the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError. Stops iterating on the first matching element.

Implementation

@override
I firstWhere(bool Function(I) test, {I Function()? orElse}) {
  late I value;
  try {
    value = colors.firstWhere(test as bool Function(O)) as I;
  } on StateError {
    if (orElse != null) {
      value = orElse();
    } else {
      rethrow;
    }
  }
  return value;
}