【问题标题】:Can I make a Dart function "wait" for a set amount of time or input?我可以让 Dart 函数“等待”一段时间或输入吗?
【发布时间】:2014-12-02 09:22:41
【问题描述】:

我正在尝试用 Dart 制作一个简单的 RPG。我需要在 div 中的屏幕上显示文本,并且我需要让程序在显示下一段文本之前等待用户输入。

例如:

void main() {
  showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
  print("showText has finished");
}

"showText has finished" 不应该显示,直到文本显示并且玩家按下回车键。这是我到目前为止的(在我看来非常丑陋的)代码:

void showText(String text) {
    var textBox = querySelector("#sample_text_id")
        ..text = "";
    var timer;
    var out;
    out = ([int i = 0]) {
        textBox.text += text[i];
        if (i < text.length - 1) timer = new Timer(const Duration(milliseconds: 10), () => out(i + 1));
    };
    out();
}

计时器异步运行out() 函数,我不希望它这样做。理想情况下,我想写这样的东西:

void showText(String text) {
    var textBox = querySelector("#sample_text_id")
            ..text = "";
    for(int i = 0; i < text.length; i++) {
        textBox.text += text[i];
        pause(const Duration(milliseconds: 10)); //  pause the program for given duration
    }
    waitFor(KeyEnum.ENTER, KeyStateEnum.DOWN); // pause until key is pressed (pseudo Enum contains char codes)
}

这可能吗?

【问题讨论】:

标签: html dart wait


【解决方案1】:

这是一个如何使用新的 async/await 功能执行此操作的示例。注意方法体开头的 async 声明,以及调用 pause() 和 showText() 之前的 await 语句。

Future pause(Duration d) => new Future.delayed(d);

Future waitFor(int c) => document.body.onKeyDown.firstWhere((e) => e.keyCode == c);

Future showText(String text) async {
    var textBox = querySelector("#sample_text_id")
            ..text = "";
    for(int i = 0; i < text.length; i++) {
        textBox.text += text[i];
        await pause(const Duration(milliseconds: 100)); //  pause the program for given duration
    }
    return waitFor(KeyCode.ENTER); // pause until key is pressed
}

main() async {
  await showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
  print("showText has finished");
}

【讨论】:

  • 谢谢。我对其进行了测试并对其进行了编辑,以便代码可以正常工作。我还用工作代码编辑了你的帖子
  • 谢谢。我不得不复制并粘贴你的编辑,因为它被过分热心的编辑警察拒绝了。
【解决方案2】:

这个pause() 函数会完全破坏您的网页。 Dart 没有线程,在此暂停期间没有其他代码可以运行(没有事件处理程序,没有 GUI 更新)。这不是浏览器中代码的工作方式。 Dart 本质上是异步的。在使用 Dart 时,熟悉这种编程风格很重要。

也就是说,Async/Await feature in Dart 1.8 的方式有所改进,这在一定程度上隐藏了异步性。

【讨论】:

    【解决方案3】:

    Stream builder 是最好的方法,请阅读:Understanding stream

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2020-07-16
      • 2012-01-24
      • 1970-01-01
      • 2020-12-27
      • 2022-07-23
      • 2020-03-02
      相关资源
      最近更新 更多