首页 > 技术文章 > 14*:Flutter之手势GestureDetector

zyzmlc 2020-12-05 11:32 原文

问题

 

目录

 

预备

 

正文

Flutter中除了少部分组件,如Button相关的组件可以直接通过onPressed实现点击事件。其余组件想实现点击、长按等事件,都需要借助GestureDetector([dɪˈtektə(r)]
:探测器; 检测器; 侦察器)
来实现手势监听

 

1:常用的几个手势

 

下面介绍比较常用的手势如onTap(点击)、onDoubleTap(双击)、onLongPress(长按)

GestureDetector(
  onTap: () => _printMsg("点击"),
  onDoubleTap: () => _printMsg("双击"),
  onLongPress: () => _printMsg("长按"),
  onTapCancel: () => _printMsg("取消"),
  onTapUp: (e) => _printMsg("松开"),
  onTapDown: (e) => _printMsg("按下"),
  child: Container(
    decoration: BoxDecoration(color: Colors.redAccent),
    width: 100,
    height: 100,
  ),
)

2:拖动手势

小球跟随手指移动的实现应该是属于各种移动端框架作为了解拖动手势的的典型案例,下面我们来看看用flutter如何实现小球跟随手指移动

拖动手势主要由onPanDown(手指按下)、onPanUpdate(手指滑动)、onPanEnd(滑动结束)构成

Stack(
  children: <Widget>[
    Positioned(
      top: top,
      left: left,
      child: GestureDetector(
        onPanDown: (DragDownDetails e) {
          //打印手指按下的位置
          print("手指按下:${e.globalPosition}");
        },
        //手指滑动
        onPanUpdate: (DragUpdateDetails e) {
          setState(() {
            left += e.delta.dx;
            top += e.delta.dy;
          });
        },
        onPanEnd: (DragEndDetails e) {
          //打印滑动结束时在x、y轴上的速度
          print(e.velocity);
        },

        child: Container(
          width: 72,
          height: 72,
          decoration: BoxDecoration(
            color: Colors.blueAccent,
            borderRadius: BorderRadius.circular(36)
          ),
        ),
      ),
    )
  ],
)

3:缩放手势

缩放手势需要用到onScaleUpdate方法,下面是一个简单的图片缩放的实现

Center(
  child: GestureDetector(
    child: Container(
      //使用OverflowBox可以让子组件宽高超过父组件
      child: OverflowBox(
        maxWidth: 2000.0,
        child: Image.network(
            "https://upload-images.jianshu.io/upload_images/10992781-a64bd14d27699266.png?imageMogr2/auto-orient/strip|imageView2/2/w/800/format/webp",
            width: width),
      ),
    ),
    onScaleUpdate: (ScaleUpdateDetails e) {
      setState(() {
        //缩放倍数在0.8到10倍之间
        width = 200 * e.scale.clamp(0.8, 10);
      });
    },
  ),
)

 

注意

 

引用

1:手势GestureDetector

推荐阅读