Flutter GestureDetector 点击空白区域无反应解决办法

在flutter中只用GestureDetector添加点击事件,发现在空白区域点击无效,事件不响应。解决办法:

GestureDetector(
    behavior: HitTestBehavior.opaque,
)

说明:

/// 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,
}

翻译一下就是:

当behavior选择 deferToChild 时,只有当前容器中的child被点击时才会响应点击事件

当behavior选择 opaque 时,点击整个区域都会响应点击事件,但是点击事件不可穿透向下传递,注释翻译:阻止视觉上位于其后方的目标接收事件,所以我需要的这种效果直接将behavior设置为HitTestBehavior.opaque就可以了;

当behavior选择 translucent 时,同样是点击整个区域都会响应点击事件,和opaque的区别是点击事件是否可以向下传递,注释翻译:半透明目标既可以在其范围内接受事件,也可以允许视觉上位于其后方的目标接收事件

Link: