1

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!

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
George Aslanis
  • 517
  • 4
  • 11

1 Answers1

0

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.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks Gunter, unfortunately readByteSync is sync/blocking and stdin does not provide all keycodes. I had to create a separate thread in native extension performing ReadConsoleInputs to get the raw virtualkeycodes directly from the input buffer. Now I need to find c/c++ sample code that demonstates how to create a Dart "stream" object, so Dart apps can listen on my new stream of ints("xin" virtualkeycodes). You know where to find such code snipets? Should I post question on Dart Misc? – George Aslanis Jul 24 '14 at 20:14
  • Sorry, I have no experience with native extensions. Just ask the question here and in the forum and create a link in the forum post to the SO question. It often helps to post the SO question to the G+ Dartisans group too. There aren't many people working on native extensions as far as I am aware of. – Günter Zöchbauer Jul 24 '14 at 20:25
  • 1
    I know this question is perhaps outdated but just for those who is probably interested in blocking solution: Setting `stdin.lineMode = false` makes value being immediately returned after a key press, without pressing `Enter`. – SdtElectronics Aug 28 '21 at 15:17