2

I want to print data.length after listening to this stream but the program executed synchronously. How can I listen to this data stream without using the await-for syntax

void main() async {
  final file = File('assets/text_long.txt');
  final stream = file.openRead();

  stream.listen(
    (data) {
      print(data.length);
    },
  );
}

Here is the output:

Exited (1)
zex_rectooor
  • 692
  • 7
  • 26

2 Answers2

1

Use asFuture method.

  final file = File('assets/text_long.txt');
  final stream = file.openRead();

  final streamSubscription = stream.listen(
    (data) {
      print(data.length);
    },
  );
  await streamSubscription.asFuture();
zex_rectooor
  • 692
  • 7
  • 26
0

Use await keyword.

await stream.listen(
    (data) {
      print(data.length);
    },
  );
Hoa Le
  • 174
  • 4