user3748198
user3748198

Reputation: 124

How to get keyboard user input within a timeframe

For example I want to provide user with a prompt print("do this within 3 seconds or time will be up.")

And when time 3 second passes, it should prompt another message saying, print("Your time is up, you failed.")

So far I have figured out to get the current time using DateTime current = new DateTime(); and the three seconds later time with DateTime threeSeconds = current.add(new Duration (seconds : 3)); but I can't figure out how to force user to enter something within those two times.

Upvotes: 0

Views: 269

Answers (2)

julemand101
julemand101

Reputation: 31209

Well, it is not clear if you want a solution which works for Dart in browser or Dart as a console application. But I hope this Dart console application example is somewhat useful for you:

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!');
  }
}

Notice that you can call the timeout() method on streams and futures. In my example I use the timeout to add a null event to my stream if no input has been given in 5 seconds.

Upvotes: 1

sao
sao

Reputation: 1821

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

You can use JavaScript with Dart now. So setTimeout might work.

There is an answer for a built in Dart operation on stack, see below

How to use setInterval/setTimeout in Dart SDK 0.4+

Upvotes: 0

Related Questions