简体   繁体   English

如何使用 flutter 检测 iPhone 键盘上按下的键?

[英]How can I detect the key pressed on an iPhone keyboard using flutter?

I am trying to detect if the backspace key has been pressed on the iPhone keyboard.我正在尝试检测是否在 iPhone 键盘上按下了退格键。 The logic I wrote works perfectly on android, but not on iPhone or the iPhone simulator.我编写的逻辑在 android 上完美运行,但在 iPhone 或 iPhone 模拟器上却不行。

this is my code:这是我的代码:

Padding(
          padding: const EdgeInsets.all(28.0),
          child: RawKeyboardListener(
            onKey: (RawKeyEvent event) {
            if(event.runtimeType == RawKeyDownEvent){
              if (event.logicalKey == LogicalKeyboardKey.backspace || event.physicalKey == PhysicalKeyboardKey.backspace) {
                _focusNodes[i]?.unfocus();
                if (i != 0) {
                  _focusNodes[i - 1]?.requestFocus();
                }
              }
            }
          },
            focusNode: FocusNode(),
            child: TextField(
               key: Key('PinInput'),
              controller: TextEditingController(),
              focusNode: FocusNode(),
            ),
          ),
        ),

This piece of code works perfectly in android, but the onKey callback in the RawKeyboardListener is not being called when I hit a key in an iPhone or iPhone simulator.这段代码在 android 中完美运行,但是当我在 iPhone 或 iPhone 模拟器中按下键时,不会调用RawKeyboardListener中的onKey回调。

How do I handle this?我该如何处理?

According to the flutter api, LogicalKeyboardKeys like you are using in your code are not supported on iOS .根据 flutter api ,像您在代码中使用的 LogicalKeyboardKeys 在 iOS 上不受支持 Learn more here . 在这里了解更多。

You can use the map to "translate" the iOS key codes to your expected LogicalKeyboardKey.您可以使用 map 将iOS 键码“翻译”为您预期的 LogicalKeyboardKey。 In this map you will find that the iOS key code 42 is what you are looking for: 42: LogicalKeyboardKey.backspace,在这个 map 中,您会发现 iOS 键码 42 是您要查找的: 42: LogicalKeyboardKey.backspace,

To use the constant, import package:flutter/services.dart.要使用常量, import package:flutter/services.dart.

Then access the top-level constant kIosToLogicalKey in your if check like this:然后在 if 检查中访问顶级常量kIosToLogicalKey ,如下所示:

if (event.logicalKey == LogicalKeyboardKey.backspace ||
    // TODO: Check if iOS key code is 42 or kIosToLogicalKey[42]  ||
    event.physicalKey == PhysicalKeyboardKey.backspace) {

FYI: I know that this is not the complete solution, however, I do not have a mac to test whether it is working anyways, but I hope this gives you the right direction to look at and go from there.仅供参考:我知道这不是完整的解决方案,但是,我没有 mac 来测试它是否正常工作,但我希望这能给你正确的方向来看待和 go 从那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM