Console application - StringDecoder stdin

﹥>﹥吖頭↗ 提交于 2019-12-25 00:18:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!