Search code examples
dartdart-pub

How do listen a keyboard event in dart console app?


All examples that I found about web and dart:html package. Can I get keyboard or mouse events from system in a desktop console program?


Solution

  • I don't think you can read mouse events, but you can read pressed key codes from stdin. For this just have to switch it "raw" mode by setting both lineMode and echoMode to false and then listening on this stream.

    Here is a simple example:

    import 'dart:async';
    import 'dart:convert';
    import 'dart:io' as io;
    
    Future main() async {
      io.stdin
        ..lineMode = false
        ..echoMode = false;
      StreamSubscription subscription;
      subscription = io.stdin.listen((List<int> codes) {
        var first = codes.first;
        var len = codes.length;
        var key;
        if (len == 1 && ((first > 0x01 && first < 0x20) || first == 0x7f)) {
          // Control code. For example:
          // 0x09 - Tab
          // 0x10 - Enter
          // 0x1b - ESC
          if (first == 0x09) {
            subscription.cancel();
          }
          key = codes.toString();
        } else if (len > 1 && first == 0x1b) {
          // ESC sequence.  For example:
          // [ 0x1b, 0x5b, 0x41 ] - Up Arrow
          // [ 0x1b, 0x5b, 0x42 ] - Down Arrow
          // [ 0x1b, 0x5b, 0x43 ] - Right Arrow
          // [ 0x1b, 0x5b, 0x44 ] - Left Arrow
          key = '${codes.toString()} ESC ${String.fromCharCodes(codes.skip(1))}';
        } else {
          key = utf8.decode(codes);
        }
        print(key);
      });
      print('Start listening');
    }
    

    You can also utilize dart_console package or adapt their readKey() method that parses control and esc codes.