firstWhere method
- booltest(
- Telement
- TorElse()?,
Finds the first element of this stream matchingtest.
Returns a future that is completed with the first element of this streamfor whichtest returnstrue.
If no such element is found before this stream is done, and anorElse function is provided, the result of callingorElsebecomes the value of the future. IforElse throws, the returnedfuture is completed with that error.
If this stream emits an error before the first matching element,the returned future is completed with that error, and processing stops.
Stops listening to this stream after the first matching element or errorhas been received.
Internally the method cancels its subscription after the first element thatmatches the predicate. This means that single-subscription (non-broadcast)streams are closed and cannot be reused after a call to this method.
If an error occurs, or if this stream ends without finding a match andwith noorElse function provided,the returned future is completed with an error.
Example:
var result = await Stream.fromIterable([1, 3, 4, 9, 12]) .firstWhere((element) => element % 6 == 0, orElse: () => -1);print(result); // 12result = await Stream.fromIterable([1, 2, 3, 4, 5]) .firstWhere((element) => element % 6 == 0, orElse: () => -1);print(result); // -1Implementation
Future<T> firstWhere(bool test(T element), {T orElse()?}) { _Future<T> future = _Future(); StreamSubscription<T> subscription = this.listen( null, onError: future._completeError, onDone: () { if (orElse != null) { _runUserCode(orElse, future._complete, future._completeError); return; } var stack = StackTrace.empty; var error = IterableElementError.noElement(); _trySetStackTrace(error, stack); _completeWithErrorCallback(future, error, stack); }, cancelOnError: true, ); subscription.onData((T value) { _runUserCode(() => test(value), (bool isMatch) { if (isMatch) { _cancelAndValue(subscription, future, value); } }, _cancelAndErrorClosure(subscription, future)); }); return future;}