防止键盘事件在 Flutter 中冒泡(传播到 parents)

Prevent keyboard event from bubbling (propagating to parents) in Flutter

我正在使用 RawKeyboardListener 来检测退出键以关闭(弹出)windows,但我不能使用事件并防止它冒泡(传播) 到 parent windows,因此所有 parent windows 将接收转义并关闭!

我尝试使用 Focus 元素,它也是 onKey,但没有区别。

return Scaffold(
  body: RawKeyboardListener(
    focusNode: FocusNode(),
    onKey: (RawKeyEvent event) {
      if (event.logicalKey == LogicalKeyboardKey.escape) {
      Navigator.pop(context);
    }},
    autofocus: true,
    child: Container(
      child: Text("blah blah")
      ),
    ),
  ),
);

您可以将按键侦听器附加到焦点节点,此侦听器将 return 确定是否处理按键事件的 KeyEventResult 枚举

   var focus = FocusNode(onKey: (FocusNode node, RawKeyEvent event) {
      if (event.logicalKey == LogicalKeyboardKey.escape)
      {
        return KeyEventResult.handled;
      }
      return KeyEventResult.ignored;
    });

这里还有 KeyEventResult 的描述:

/// An enum that describes how to handle a key event handled by a
/// [FocusOnKeyCallback].
enum KeyEventResult {
  /// The key event has been handled, and the event should not be propagated to
  /// other key event handlers.
  handled,
  /// The key event has not been handled, and the event should continue to be
  /// propagated to other key event handlers, even non-Flutter ones.
  ignored,
  /// The key event has not been handled, but the key event should not be
  /// propagated to other key event handlers.
  ///
  /// It will be returned to the platform embedding to be propagated to text
  /// fields and non-Flutter key event handlers on the platform.
  skipRemainingHandlers,
}