Flutter中如何获取手势位置

今天遇到一个需求,在ListView中长按每个Item就弹出一个带有删除字样的PopUpMenuItem。类似于下图所示:

《Flutter中如何获取手势位置》 弹出删除按钮

对每个Item使用GestureDetector包裹之后,发现其OnLongPress方法中不提供位置信息。
但是翻了源码之后,发现onPanDown好像可以使用。

/// A pointer has contacted the screen and might begin to move.
  final GestureDragDownCallback onPanDown;

所以我们可以在onPanDown中获取位置,然后在onLongPress中使用这个位置。

《Flutter中如何获取手势位置》 测试

然后就能够使用这个位置信息来展示PopUpItem了。
完整源码如下

//获取点击的位置
      onPanDown: (details) {
        x = details.globalPosition.dx;
        y = details.globalPosition.dy;
      },
      onLongPress: () async{
        if (Platform.isAndroid){
          final result = await showMenu(
              context: context,
              items: [PopupMenuItem(child: Text("删除"), value: ItemType.delete,)],
              position: RelativeRect.fromLTRB(
                  x, y - 50, MediaQuery.of(context).size.width - x, 0));
          if (result == ItemType.delete){
            setState(() {
                //执行删除数据操作
              });
          }
        }
      },
    原文作者:Rreply
    原文地址: https://www.jianshu.com/p/0b1b3c4a400d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞