【问题标题】:How to get keyboard user input within a timeframe如何在时间范围内获取键盘用户输入
【发布时间】:2019-09-11 18:42:03
【问题描述】:

例如,我想为用户提供提示 print("do this within 3 seconds or time will be up.")

当时间 3 秒过去时,它应该提示另一条消息说, print("Your time is up, you failed.")

到目前为止,我已经想出使用DateTime current = new DateTime(); 获取当前时间,使用DateTime threeSeconds = current.add(new Duration (seconds : 3)); 获取三秒后的时间,但我无法弄清楚如何强制用户在这两次内输入内容。

【问题讨论】:

  • 大多数 javascript 库都有计时器和在一段时间后触发事件的能力,也许看看 setTimeout 是否可以工作,但它不是 Dart 特定的

标签: dart


【解决方案1】:

嗯,目前尚不清楚您是否想要一个适用于浏览器中的 Dart 或将 Dart 作为控制台应用程序的解决方案。但我希望这个 Dart 控制台应用程序示例对您有所帮助:

import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  print('You have 5 seconds! WHAT IS YOUR NAME!!!!');
  final name = await stdin
      .transform(const Utf8Decoder())
      .transform(const LineSplitter())
      .timeout(const Duration(seconds: 5), onTimeout: (sink) => sink.add(null))
      .first;

  if (name == null) {
    print('LOL WUT DO YOUR NOT EVEN KNOW YOUR NAME!!!!');
  } else {
    print('I knew it. Your name is $name!');
  }
}

请注意,您可以在流和期货上调用 timeout() 方法。在我的示例中,如果 5 秒内没有输入,我使用超时向我的流添加一个空事件。

【讨论】:

    【解决方案2】:

    https://news.dartlang.org/2012/09/use-javascript-code-in-your-dart-apps.html

    您现在可以在 Dart 中使用 JavaScript。所以 setTimeout 可能会起作用。

    在堆栈上内置 Dart 操作有一个答案,见下文

    How to use setInterval/setTimeout in Dart SDK 0.4+

    【讨论】:

      猜你喜欢
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多