firstOrNull property

Future<T?> get firstOrNull

A future which completes with the first event of this stream, or with null.

This stream is listened to, and if it emits any event, whether a data event or an error event, the future completes with the same data value or error. If the stream ends without emitting any events, the future is completed with null.

Implementation

Future<T?> get firstOrNull {
  var completer = Completer<T?>.sync();
  final subscription = listen(null,
      onError: completer.completeError,
      onDone: completer.complete,
      cancelOnError: true);
  subscription.onData((event) {
    subscription.cancel().whenComplete(() {
      completer.complete(event);
    });
  });
  return completer.future;
}