0

I am new in dart and creating a console game. we have: int score = 0; i should give every time a number from user in console environment. if user input a number than score plus one... and if user did not input anything and he did not touch his keyboard after 5 seconds the score should be minus one.

please help!

I tried this page sulotion: How to get keyboard user input within a timeframe but when use that code in a loop to run the other round of game as you see below:

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

Future<void> main() async {
  for(var i = 0; i < 10; i++) {
    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('2'))
        .first;

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

that give me this error:

Unhandled exception:
Bad state: Stream has already been listened to.
#0      _StreamController._subscribe (dart:async/stream_controller.dart:676:7)
#1      _ControllerStream._createSubscription (dart:async/stream_controller.dart:827:19)
#2      _StreamImpl.listen (dart:async/stream_impl.dart:471:9)
#3      _Socket.listen (dart:io-patch/socket_patch.dart:2184:31)
#4      _StdStream.listen (dart:io/stdio.dart:22:20)
#5      new _SinkTransformerStreamSubscription (dart:async/stream_transformers.dart:49:16)
#6      _BoundSinkStream.listen (dart:async/stream_transformers.dart:171:9)
#7      new _SinkTransformerStreamSubscription (dart:async/stream_transformers.dart:49:16)
jessi cas
  • 21
  • 2
  • See https://stackoverflow.com/a/67863651/ and [How to get keyboard user input within a timeframe](https://stackoverflow.com/q/57895068/). – jamesdlin Dec 15 '22 at 04:36
  • @jamesdlin i tried that but when i put it in a loop that give me error Bad state: Stream has already been listened to... (added error in question text) – jessi cas Dec 15 '22 at 04:59
  • The answer I linked to specifically uses a `StreamQueue` to avoid that problem. – jamesdlin Dec 15 '22 at 05:33

0 Answers0