为什么FocusOnKeyCallback返回布尔值?

时间:2019-12-02 05:21:05

标签: flutter dart

这是FocusOnKeyCallback的dartdoc和声明:

/// Signature of a callback used by [Focus.onKey] and [FocusScope.onKey]
/// to receive key events.
///
/// The [node] is the node that received the event.
typedef FocusOnKeyCallback = bool Function(FocusNode node, RawKeyEvent event);

该回调具有bool的返回类型,但是尚不清楚如何使用该值。 void会在这里工作吗?

(最初在Flutter的GitHub上问:https://github.com/flutter/flutter/issues/45367

1 个答案:

答案 0 :(得分:1)

它返回bool以标记该事件已由任何焦点节点处理,如果不是,则调用断言。看看_handleRawKeyEvent类的FocusManager方法:

    ...

    bool handled = false;
    for (FocusNode node in <FocusNode>[_primaryFocus, ..._primaryFocus.ancestors]) {
      if (node.onKey != null && node.onKey(node, event)) {
        assert(_focusDebug('Node $node handled key event $event.'));
        handled = true;
        break;
      }
    }
    if (!handled) {
      assert(_focusDebug('Key event not handled by anyone: $event.'));
    }

    ...

因此,基本上是防止onKey事件传播。