George Aslanis
George Aslanis

Reputation: 527

Dart:io stdin raw character codes

I've created a Dart console app and need to process keycodes like Arrow keys and function keys from stdin? The samples I've seen are typically String based :

Stream readLine() => stdin.transform(UTF8.decoder).transform(new LineSplitter());
readLine().listen(processLine);

I modified the above sample hoping to get the raw ints like this:

Stream readInts() => stdin;
readInts().listen(processInts);
void processInts(List<int> kbinput) {
    for (int i=0;i<kbinput.length;i++){
    print ("kbinput:${kbinput[i]}");
    }
}

It seems stdin provides only printable characters and not all ascii keycodes. If it is not possible from stdin, can I create & load a stream within my native extension with the keycodes? How can my console app get to the ascii keycodes of any keypress? Thanks for your help!

Upvotes: 1

Views: 926

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657937

One way would be

import 'dart:io' as io;
import 'dart:convert' show UTF8;

void main() {
  io.stdin.echoMode = false;
  var input;
  while(input != 32) { // leave program with [Space][Enter]
    input = io.stdin.readByteSync();
    if(input != 10)  print(input); // ignore [Enter]
  }
  io.stdin.echoMode = true;
}

but it only returns a value after Enter is pressed. For one key press it returns from one up to three bytes.

It seems it's not easy to get a keystroke from console without pressing Enter
see Capture characters from standard input without waiting for enter to be pressed for more details. You could create a native extension that implements the suggested solution in the linked question.

Upvotes: 0

Related Questions