如何在时间范围内获取键盘用户输入

时间:2019-09-11 18:42:03

标签: dart

例如,我想向用户提供提示 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)); 来获取三秒之后的时间,但是我不知道如何在这两次时间内强迫用户输入内容

2 个答案:

答案 0 :(得分: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秒钟内未输入任何信息,我将使用超时向流中添加null事件。

答案 1 :(得分:0)

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+