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

Posted

技术标签:

【中文标题】防止键盘事件在 Flutter 中冒泡(传播给父母)【英文标题】:Prevent keyboard event from bubbling (propagating to parents) in Flutter 【发布时间】:2021-07-01 21:52:46 【问题描述】:

我正在使用 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")
      ),
    ),
  ),
);

【问题讨论】:

“我正在使用 RawKeyboardListener 检测转义键” - 您的代码不会以任何方式检测转义键:您无条件调用 pop() 方法 只是问题中的错字,已更新,谢谢。 事件不会冒泡到父窗口(页面):现在你的onKey 被调用了两次(用于按键向下和向上) 是的,冒泡了,我加了日志。 【参考方案1】:

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

【讨论】:

以上是关于防止键盘事件在 Flutter 中冒泡(传播给父母)的主要内容,如果未能解决你的问题,请参考以下文章

事件冒泡和阻止事件冒泡

理解js事件冒泡事件委托事件捕获

事件冒泡 & 阻止事件冒泡

单击点透

js学习笔记26----事件冒泡,事件捕获

JavaScript事件冒泡及使用jQuery阻止