Stream<T>.error constructor Null safety

  1. @Since("2.5")
  1. Object error,
  2. [StackTrace? stackTrace]

Creates a stream which emits a single error event before completing.

This stream emits a single error event of error and stackTrace and then completes with a done event.


Future<void> tryThings(Stream<int> data) async {
  try {
    await for (var x in data) {
      print('Data: $x');
  } catch (e) {
tryThings(Stream<int>.error('Error')); // prints "Error".

The returned stream is effectively equivalent to one created by Future<T>.error(error, stackTrace).asStream(), by or (() async* { throw error; } ()), except that you can control the stack trace as well.


factory Stream.error(Object error, [StackTrace? stackTrace]) {
  // TODO(40614): Remove once non-nullability is sound.
  checkNotNullable(error, "error");
  return (_AsyncStreamController<T>(null, null, null, null)
        .._addError(error, stackTrace ?? AsyncError.defaultStackTrace(error))