防止键盘事件在 Flutter 中冒泡传播给父母

问题描述

我正在使用 RawKeyboardListener 检测关闭(弹出)窗口的转义键,但我不能使用该事件并防止它冒泡(传播)到父窗口,因此所有父窗口将接收逃逸并关闭

我尝试使用 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")
      ),),);

解决方法

您可以将键侦听器附加到焦点节点,此侦听器将返回一个 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,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,}