#Flutter手势中的 Behavior

2020-03-30  本文已影响0人  海青

Flutter手势中的behavior

前言:本杂文的阅读者需要掌握Flutter界面布局基本技巧,会使用Widget组合界面,否则无法理解下文。

Flutter中的手势事件Widget包括:Listener(监听触摸,鼠标事件),MouseRegion(监听鼠标部分事件) 两大基本类。

我们今天所说的behaivor属性是HitTestBehavior,控制手势点击测试行为。它是一个枚举。

/// How to behave during hit tests.
enum HitTestBehavior {
  /// Targets that defer to their children receive events within their bounds
  /// only if one of their children is hit by the hit test.
  deferToChild,

  /// Opaque targets can be hit by hit tests, causing them to both receive
  /// events within their bounds and prevent targets visually behind them from
  /// also receiving events.
  opaque,

  /// Translucent targets both receive events within their bounds and permit
  /// targets visually behind them to also receive events.
  translucent,
}

说明:此处的“空白位置”也就是FlutterChina中第八章中提到的“透明区域”,“透明区域”有些概念模糊。我已提出建议改成 hitTest测试失败的组件,有人说按照“空白位置”的说法,这不是也不对吗,其实不然,hitTest测试失败的组件其实就是指的上层Listener组件,点击测试失败。“空白位置”是在Listener内部范围说的概念,指Listener的子Widget没有占据的范围,解释范围不一样。如果你在Listener内部添加了等大小的透明mask 组件,比如透明的DecoratedBox,但是DecoratedBox点击测试成功,这就无法实现translucent的点击穿透的效果。

附上Listener 点击测试相关源码可以理解更透测:

  @override
  bool hitTest(BoxHitTestResult result, { Offset position }) {
    bool hitTarget = false;
    if (size.contains(position)) {
      hitTarget = hitTestChildren(result, position: position) || hitTestSelf(position);
      if (hitTarget || behavior == HitTestBehavior.translucent)
        result.add(BoxHitTestEntry(this, position));
    }
    return hitTarget;
  }

  @override
  bool hitTestSelf(Offset position) => behavior == HitTestBehavior.opaque;

说明:hitTarget,就是表明是否测试成功。首先得点击Position 在Size范围内。然后优先看子Widget是否点击测试成功,不成功再看hitTestSelf 是否成功,此处就是 behavior == HitTestBehavior.opaque 就返回成功,对应我们所说无条件点击测试成功。
再就是根据hitTarget测试结果判断是否把当前Listener添加到相应链result中,如果hitTarget == false,则判断behavior 是否为 HitTestBehavior.translucent,若是则也添加到响应链中,但是却返回点击测试失败,这就和上面介绍的translucent相符。

上一篇下一篇

猜你喜欢

热点阅读