3

我在这里找到了能够从控制台读取的答案:Is it possible to read from console in Dart? . 但是,我想阻止程序中的进一步执行,直到输入字符串(想想只是与用户进行简单的控制台交互)。

但是,我没有看到一种方法来控制简单交互的执行流程。我意识到 Dart I/O 是异步的,所以我正在努力弄清楚我应该如何完成这个看似简单的任务。只是我试图将 Dart 用于它不打算做的事情吗?

#import("dart:io");

void main() {
  var yourName;
  var yourAge; 
  var console = new StringInputStream(stdin);

  print("Please enter your name? ");
  console.onLine = () {
    yourName = console.readLine();
    print("Hello $yourName");
  };

  // obviously the rest of this doesn't work...
  print("Please enter your age? ");
  console.onLine = () { 
    yourAge = console.readLine();
    print("You are $yourAge years old");
  };

  print("Hello $yourName, you are $yourAge years old today!");
}
4

2 回答 2

4

(回答我自己的问题)

自从最初提出这个问题以来,Dart 添加了几个功能,特别是使用标准输入的 readLineSync 的概念。本教程涵盖了编写命令行 Dart 应用程序时可能需要注意的几个典型主题:https ://www.dartlang.org/docs/tutorials/cmdline/

import "dart:io";

void main() {
    stdout.writeln('Please enter your name? ');
    String yourName = stdin.readLineSync();
    stdout.writeln('Hello $yourName');

    stdout.writeln('Please enter your age? ');
    String yourAge = stdin.readLineSync();
    stdout.writeln('You are $yourAge years old');

    stdout.writeln('Hello $yourName, you are $yourAge years old today!');
}
于 2014-01-06T19:53:18.583 回答
3

希望以后所有的IO都通过Futures来完成。与此同时,您有两种选择:

  1. 正如您在问题中所写的那样,使用回调。Futures 不是处理异步执行的唯一方法。事实上,你问我有点惊讶,因为你的问题已经包含这个答案——只需稍微移动你的代码:

    void main() {
      var stream = new StringInputStream(stdin); 
      stream.onLine = () { 
        var myString = stream.readLine();
        print("This was after the handler $myString");
    
        // I want to wait until myString is typed in
    
        print("echo $myString"); // should not print null
      }; 
    }
    
  2. 编写您自己的包装器返回Future. 它可能看起来像这样(警告:没有测试它!):

    class MyStringInputStream {
      final StringInputStream delegate;
    
      MyStringInputStream(InputStream stream)
          : delegate = new StringInputStream(stream);
    
      Future<String> readLine() {
        final completer = new Completer<String>();
    
        delegate.onLine = () {
          final line = delegate.readLine();
          delegate.onLine = null;
          completer.complete(line);
        };
    
        return completer.future;
      }
    }
    
于 2012-06-05T06:44:10.473 回答