Flutter

Flutter中Text占用一整行可点击

2021-07-06  本文已影响0人  混不吝丶

前言

在开发中常常需要设置一整行的text都可以点击,以响应用户的操作,如果只指定text所占用的空间大小可点击,那么点击区域会非常小

在一个column内一个Text可点击,我们的代码如下

 Expanded(
            child: GestureDetector(
              onTap: ()=> Navigator.pop(context),
              child: Text(
                  "取消",
                  style: TextStyle(
                      color: Color.fromRGBO(142, 142, 147, 1),
                      fontSize: 15,
                      backgroundColor: Colors.red
                  ),
                ),
            ),
          )

通过上面的代码发现Text的点击区域只有Text所占用的大小,并非整行都可点击,我们思考后认为需要一个盒模型拉伸宽度,又写下如下代码

 Expanded(
            child: GestureDetector(
              onTap: ()=> Navigator.pop(context),
              child: Container(
                color: Colors.greenAccent,
                width: double.infinity,
                alignment: Alignment.center,
                child: Text(
                  "取消",
                  style: TextStyle(
                      color: Color.fromRGBO(142, 142, 147, 1),
                      fontSize: 15,
                      backgroundColor: Colors.red
                  ),
                ),
              ),
            ),
          )

本以为以解决这个问题,运行后发现盒模型的宽度是屏幕的宽度了,但text的点击区域依然是Text占用的本身大小的区域,这是为什么呢,经过查找发现GestureDetector内的behavior在作祟,这个behavior默认为deferToChild,也就是响应子控件的大小,并非整个大小。
调整后的代码

Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: ()=> Navigator.pop(context),
              child: Container(
                color: Colors.greenAccent,
                width: double.infinity,
                alignment: Alignment.center,
                child: Text(
                  "取消",
                  style: TextStyle(
                      color: Color.fromRGBO(142, 142, 147, 1),
                      fontSize: 15,
                      backgroundColor: Colors.red
                  ),
                ),
              ),
            ),
          )

重点为behavior属性,设置opaque使整个container可响应点击
附上源码

/// 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,  // 既可以在其范围内接收事件,也可以允许事件目标也接收事件
}
上一篇下一篇

猜你喜欢

热点阅读