firstWhere method
- bool test(
- E element
- {E orElse( )?}
inherited
Returns 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.
Implementation
E firstWhere(bool test(E element), {E Function()? orElse}) { int length = this.length; for (int i = 0; i < length; i++) { E element = elementAt(i); if (test(element)) return element; if (length != this.length) { throw ConcurrentModificationError(this); } } if (orElse != null) return orElse(); throw IterableElementError.noElement(); }
© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dart.dev/stable/2.17.0/dart-collection/ListQueue/firstWhere.html