【问题标题】:How do listen a keyboard event in dart console app?如何在 dart 控制台应用程序中监听键盘事件?
【发布时间】:2020-02-23 13:20:51
【问题描述】:

我找到的关于 web 和 dart:html 包的所有示例。我可以在桌面控制台程序中从系统获取键盘或鼠标事件吗?

【问题讨论】:

    标签: dart dart-pub


    【解决方案1】:

    我认为您无法读取鼠标事件,但您可以读取来自stdin 的按键代码。为此,只需将lineModeechoMode 都设置为false,然后在此流上收听,即可将其切换为“原始”模式。

    这是一个简单的例子:

    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');
    }
    

    您还可以使用dart_console 包或改编他们的readKey() 方法来解析控制和es​​c 代码。

    【讨论】:

    • 谢谢。这是正确有用的建议和方向。不幸的是 InelliJ 运行控制台返回异常StdinException: Error setting terminal line mode, OS Error: Inappropriate ioctl for device, errno = 25。这不方便调试,但这不是问题。
    • @Makdir 是的,这是我无法解决的问题。在 IntelliJ 中应该可以使用 -Drun.processes.with.pty=true VM 选项,但它没有。所以,只能从真正的终端运行。
    • 有没有办法获得“key up”事件?
    • 我提交了一个无法从 IDE 运行的错误:issuetracker.google.com/issues/219274483
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2013-06-20
    • 2023-03-28
    • 2013-02-17
    • 2011-07-25
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多