2

Is there a way of taking single character (integer) keyboard inputs from the user and storing them to a variable in a Dart command-line app? I've tried something like:

Stream cmdLine = stdin
  .transform(new StringDecoder())
  .transform(new LineTransformer());

StreamSubscription cmdSubscription = cmdLine.listen(
  (line) => (choice = line);
  cmdSubscription.cancel(););

In an attempt to store a keyboard input into the variable 'choice' and many slight variations of this code but can't get it to work.

Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
Instinct
  • 349
  • 1
  • 3
  • 10

1 Answers1

2

Currently you can only read a whole line at a time - i.e. once enter is pressed.

Star this issue.

Updated:

The readLine() function waits for a line of input from a user and returns it as a string.

import 'dart:async';
import 'dart:io';

main() {
    print('1 + 1 = ...');
    readLine().then((line) {
        print(line.trim() == '2' ? 'Yup!' : 'Nope :(');
    });
}

Future<String> readLine() {
    var completer = new Completer<String>();

    var input = stdin
        .transform(new StringDecoder())
        .transform(new LineTransformer());

    var subs;
    subs = input.listen((line) {
        completer.complete(line);
        subs.cancel();
    });

    return completer.future;
}
Greg Lowe
  • 15,430
  • 2
  • 30
  • 33
  • That would be fine with me, just looking for the user to type a 1 or 2 then enter ;D – Instinct May 01 '13 at 05:39
  • I've added an example that does this - give me a shout if it's broken. – Greg Lowe May 01 '13 at 05:57
  • Hhmm trying to use the function but the code seems to skip past the readLine call readLine().then((s) without waiting on input. Inside that call I'm trying to set a global variable choice equal to s so I have: readLine().then((s) { choice = s; }); while (choice == 0) { } print('YOU ENTERED $choice'); trying to use the while loop to force a wait on input but still after entering anything and pushing enter it never ends up reaching the print statement. And if I remove the while loop it just hits the print without waiting on input. Am I implementing incorrectly? – Instinct May 01 '13 at 19:31
  • Forgot to mention I initialized: "var choice = 0;" earlier on – Instinct May 01 '13 at 19:40
  • Testing with print statements in different spots, I see the "choice = s;" part of the code inside the readLine call never gets reached, and I think the subs = input.listen((line) { completer.complete(line); subs.cancel(); }); also never runs – Instinct May 01 '13 at 19:44
  • Works for me ;) I've now posted a full example showing how to use it. It uses the dart Future api, have a look at this article. http://www.dartlang.org/articles/using-future-based-apis/ – Greg Lowe May 02 '13 at 21:52