Flutter中如何实现仅父容器可点击、子容器不响应点击事件?
解决方法
有两种常用实现方案,按需选择即可:
方案1:使用IgnorePointer(推荐)
直接给子容器套上IgnorePointer组件,它会忽略自身及子节点的所有指针事件,点击子区域时不会触发父容器的点击回调,实现成本最低、性能最优。
示例代码:
InkWell( onTap: (){ print('Container Clicked'); }, child: Container( height: 400, width: 400, color: Colors.blue, child: Center( child: IgnorePointer( child: Container( height: 200, width: 200, color: Colors.green, ), ), ), ), )
方案2:子容器消费点击事件
如果后续需要子容器响应部分指针事件(如长按、双击),仅需要屏蔽父容器的点击触发,可以给子容器套GestureDetector,给onTap设置空实现消费点击事件,阻止事件冒泡到父层。
示例代码:
InkWell( onTap: (){ print('Container Clicked'); }, child: Container( height: 400, width: 400, color: Colors.blue, child: Center( child: GestureDetector( onTap: () {}, child: Container( height: 200, width: 200, color: Colors.green, ), ), ), ), )
内容的提问来源于stack exchange,提问作者Siddharth Mehra
相关产品推荐
相关产品推荐

