How to return a Stream in Dart without looping through it

Issue

I have a Stream in my code, which I’ve done some modifications / transformations to. I’d like to return that Stream as the result of my function.

This code works:

Stream<int> returnStream2() async* {
  var list = <int>[1,2,3];
  var result = Stream<int>.fromIterable(list);
  await for( var i in result ) {
    yield i;
  }
}

Why doesn’t this simpler and more readable version work?

Stream<int> returnStream1() async* {
  var list = <int>[1,2,3];
  var result = Stream<int>.fromIterable(list);
  return result;
}

I get an error message "Can’t return a value from a generator function (using the ‘async*’ modifier)

Solution

Either use yield* as you already discovered, or just don’t make the function an async* function. If this stream is the only thing you yield, you can just do:

Stream<int> returnStream1() {
  var list = <int>[1,2,3];
  var result = Stream<int>.fromIterable(list);
  return result;
}

If you do other things, then yield* stream; or await for (var event in stream) yield event; are both options (they differ in how they handle error events from the stream, but for plain data events the two should be equivalent).

Answered By – lrn

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *