问题
The following or similar was shown for terminal input, however terminating input with ctl-d is not good. Is there another way to exit from this "loop"?
import "dart:io";
void main() {
stdout.write("Enter Data : ");
new StringDecoder().bind(stdin).listen((String sInput){});
//// Do something with sInput ............
}
回答1:
You can terminate a dart program by running the exit
method when using dart:io
void exit(int status)
Exit the Dart VM process immediately with the given status code.
This does not wait for any asynchronous operations to terminate.
Using exit is therefore very likely to lose data.
From the docs
That code would go inside a check in the event handler in listen
回答2:
A few options come to mind. First, you could use takeWhile()
to set a 'done' condition:
new StringDecoder().bind(stdin)
.takeWhile((s) => s.trim() != 'exit')
.listen((sInput) {
That will use the same onDone
handler (if one is set) when the user inputs the EOF
character or types exit
followed by the enter key. You can have more flexibility by cancelling the subscription with cancel()
:
void main() {
stdout.write("Enter Data : ");
var sub;
sub = new StringDecoder().bind(stdin).listen((String sInput) {
if (sInput.trim() == 'exit' || sInput.trim() == 'bye')
sub.cancel();
// Do something with sInput ............
});
Cancelling the subscription doesn't close the Stream, so any onDone
handler isn't called.
Of course, if you've got nothing left to do, you can always terminate with exit(0)
[1].
来源:https://stackoverflow.com/questions/16428292/console-application-stringdecoder-stdin