flutter gesture空白区域不响应ontap解决方法

楚天乐 6110 0 条

问题描述

Widget buildServerItem(BuildContext context, Server server){
  return Column(
    children: <Widget>[
      seperateLine,
      Container(
        padding: const EdgeInsets.only(top:15.0, left:20.0, right:20.0, bottom: 15.0),
        child: GestureDetector(![QQ截图20191030163401.png][1]
          onTap:() => print("say hello"),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Row(
                  children: <Widget>[
                    Image.asset("assets/images/server.png"),//Icon(Icons.storage, color:Color(0xFF0F81FE)),
                    Padding(padding: const EdgeInsets.only(left:10.0),),
                    Text(server.name, style:TextStyle(fontSize: 18, color:Color.fromARGB(0xff, 0x33, 0x33, 0x33), fontWeight: FontWeight.normal)),
                  ],
                )
              ),
            ],
          ),
        ),
      ),
    ],
  );
}

显示效果如下图

QQ截图20191030163400.png

问题,点击row中空白区域ontap不响应

QQ截图20191030163401.png

解决方案

给Gesture添加behavior: HitTestBehavior.opaque,

child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap:() => StoreProvider.of<AppState>(context).dispatch(new SelectServerAction(id: server.id)),
           ......

为什么

HitTestBehavior可选值:deferToChild,opaque,translucent,values

deferToChild: Targets that defer to their children receive events within their bounds only if one of their children is hit by the hit test. 事件发送给子元素处理,空白区域没有被子元素占据,自然无法响应

opaque: 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. 说的很清楚了,我们需要的就是这个。整个区域做不透明对象处理,全都可以响应到事件

translucent: Translucent targets both receive events within their bounds and permit targets visually behind them to also receive events. 半透明时候,顶部组件和底层组件都可以接收到响应事件

values: A constant List of the values in this enum, in order of their declaration. 提供一个列表?指定可接受对象?暂时忽略吧

参考链接

https://api.flutter.dev/flutter/rendering/HitTestBehavior-class.html



发表我的评论
昵称 (必填)
邮箱 (必填)
网址
执行时间: 54.466009140015 毫秒