What is the use of await stdin.first in dart


In the below program seem that the statement await stdin.first; waits for the user to hit enter.
But how its working I don’t understand. await is used before stdin.first this means that this method must returns a Future but how its working can’t get it.

void main(final List<String> $) async {
  print("Entering main");
  stdout.write("Press Enter key to terminate the program : ");
  await stdin.first;
  print("Exiting main");

How is the await stdin.first; statement works?

>Solution :

The stdin is a Stream<String>. That means it sends string events when there is input on standard in of the process.

You won’t get an event for each character, the input is buffered, but traditionally the input buffer will be flushed on each newline.
(It might also be flushed before, if input starts out with a lot of characters on the same line, filling up the buffer, but let’s assume that doesn’t happen.)
So, the first event on the stdin stream comes when the first newline is arrives, which, if standard in use connected to the user terminal, is when the user presses return.

The first getter on a stream will listen to the stream, emit the first event, and then close the stream afterwards. Since the event arrives asynchronously, first returns a Future<String> immediately when it’s called, and then completes the future when the stream event arrives.
The await waits for that future to be completed, which will happen soon after the user has has pressed return.

Leave a ReplyCancel reply