Flutter使嵌套的GestureDetector都可以收到点击事件

如下面的普通写法,只有内部的 GestureDetector可以接收事件,而外部的GestureDetector是收不到事件的。

 

GestureDetector(
    onTap: () {
      print('tap on parent');
    },
    child: Container(
      width: 100,
      height: 100,
      color: Colors.blue,
      child: GestureDetector(
        onTap: () {
          print('tap on child');
        },
        child: Center(
          child: Container(
            width: 50,
            height: 50,
            color: Colors.orange,
          ),
        ),
      ),
    ))

下面是使内外GestureDector都可以接收到事件的实现方式:


RawGestureDetector(
    gestures: {
      AllowMultipleGestureRecognizer: GestureRecognizerFactoryWithHandlers<AllowMultipleGestureRecognizer>(
        () => AllowMultipleGestureRecognizer(),
        (AllowMultipleGestureRecognizer instance) {
          instance.onTap = () => print('tap on parent ');
        },
      )
    },
    behavior: HitTestBehavior.opaque,
    //Parent Container
    child: Container(
      width: 100,
      height: 100,
      color: Colors.blue,
      child: GestureDetector(
        onTap: () {
          print('tap on child');
        },
        child: Center(
          child: Container(
            width: 50,
            height: 50,
            color: Colors.orange,
          ),
        ),
      ),
    )),



class AllowMultipleGestureRecognizer extends TapGestureRecognizer {
  @override
  void rejectGesture(int pointer) {
    acceptGesture(pointer);
  }
}

实现原理参考:

解析Flutter中的手势控制Gestures_吉原拉面-CSDN博客_flutter gesture  Flutter提供了很多处理触摸事件的控件,例如InkWell和InkResponse可以处理点击、双击、长按等事件,将它们包裹在需要响应触摸事件的控件外部就可以了,而且InkWell和InkResponse还会添加一个水波纹的点击效果,InkResponse还可以设置水波纹的形状。但是,InkWell和InkResponse都不会做任何的渲染工作,它们只是更新了父级Material Widg...https://blog.csdn.net/yumi0629/article/details/82867108 重点如下:

     父控件和子控件都会有自己的recognizers被传递到Arena这里,只有一个recognizers会取胜,而且大部分情况下胜者都是子控件。

      解决方法就是使用你自定义的RawGestureDetector,强行改变Arena的行为。

      acceptGesture()是在给定的pointer id获胜(win)时的回调;rejectGesture()是在给定的pointer id失败(lose)时的回调。所以我们在自定义的recognizer中,强行在rejectGesture()中做了accept操作。
  然后,我们在控件中,将我们的自定义gesture-recognizer,通过GestureRecognizerFactoryWithHandlers传递给RawGestureDetector:。
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值