【问题标题】:Console application - StringDecoder stdin控制台应用程序 - StringDecoder 标准输入
【发布时间】:2013-05-07 20:48:44
【问题描述】:

对于终端输入显示了以下或类似的内容,但是使用 ctl-d 终止输入并不好。还有其他方法可以退出这个“循环”吗?

import "dart:io";

void main() {
  stdout.write("Enter Data : ");
  new StringDecoder().bind(stdin).listen((String sInput){});
////  Do something with sInput ............
}  

【问题讨论】:

  • 当你说“不好”时,你是什么意思?
  • @jdigital。我只是想让“操作员”点击“输入”,然后使用输入的数据。

标签: dart dart-io


【解决方案1】:

您可以在使用 dart:io 时通过运行 exit 方法来终止 dart 程序

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

该代码将进入 listen 中的事件处理程序的检查中

【讨论】:

    【解决方案2】:

    我想到了几个选项。首先,您可以使用takeWhile() 设置“完成”条件:

    new StringDecoder().bind(stdin)
      .takeWhile((s) => s.trim() != 'exit')
      .listen((sInput) {
    

    当用户输入EOF 字符或键入exit 后跟回车键时,这将使用相同的onDone 处理程序(如果已设置)。您可以通过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 ............
      });
    

    取消订阅不会关闭 Stream,因此不会调用任何 onDone 处理程序。

    当然,如果您无事可做,您可以随时以exit(0) [1] 结束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2013-09-27
      • 2010-11-06
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      相关资源
      最近更新 更多