如何在Dart中模拟StringInputStream readLine上的阻塞?

时间:2012-06-04 17:25:46

标签: console dart

我找到了能够从控制台阅读的答案: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!");
}

2 个答案:

答案 0 :(得分:4)

(回答我自己的问题)

自从最初询问这个问题以来,Dart已经添加了几个功能,特别是使用stdin的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!');
}

答案 1 :(得分:3)

我希望将来所有IO都可以通过Future来完成。与此同时,您有两种选择:

  1. 在您提出问题时使用回调。 Future不是处理异步执行的唯一方法。事实上我有点意外,因为你的问题已经包含了这个答案 - 只需稍微移动你的代码:

    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;
      }
    }