Created
March 9, 2021 12:24
-
-
Save frencojobs/dca6a24e07ada2b9df1683ddc8fa45c6 to your computer and use it in GitHub Desktop.
Dart read from console line by line asynchronously.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:convert'; | |
import 'dart:io' as io; | |
/// Reads a single line from [stdin] asynchronously. | |
Future<String> readLine() async { | |
final c = Completer<String>(); // completer | |
final l = io.stdin // stdin | |
.transform(utf8.decoder) // decode | |
.transform(const LineSplitter()) // split line | |
.asBroadcastStream() // make it stream | |
.listen((line) => !c.isCompleted ? c.complete(line) : 0); // listen | |
final o = await c.future; // get output from future | |
l.cancel(); // cancel stream after future is completed | |
return o; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What works for me at Dart SDK version: 2.19.4 (stable):
In the original example subsequent invocations of the readLine() function will cause
Bad state: Stream has already been listened to.
error to be thrown. It seems it is not possible to cancel a subscription to stdin. This code also throws the same error (on both Linux and Windows):