简体   繁体   English

如何检测flutter中的左右滑动?

[英]How to detect left and right swipes in flutter?

I am using GestureDetector to check when a user swipes horizontally across the screen.我正在使用 GestureDetector 检查用户何时在屏幕上水平滑动。

The swipe should only be registered when the user removes their finger from the screen to end the swipe, hence the use of onHorizontalDragEnd.仅当用户将手指从屏幕上移开以结束滑动时才应注册滑动,因此使用 onHorizontalDragEnd。

When the swipe ends a int is incremented resulting in a new image being displayed.当滑动结束时,一个 int 会增加,从而显示一个新图像。

The issue I am having is that I want to be able to let the user swipe left to go back an image.我遇到的问题是我希望能够让用户向左滑动到 go 返回图像。

How can I detect which direction a user has swiped when implementing onHorizontalDragEnd?实现 onHorizontalDragEnd 时如何检测用户滑动的方向?

Use GestureDetector .使用GestureDetector Example例子

GestureDetector(
      onHorizontalDragEnd: (dragDetail) {
        if (dragDetail.velocity.pixelsPerSecond.dx < 1) {
          print("right");
        } else {
          print("left");
        }
      },
      child: Container(...),
    );

Having GestureDetector , you can use onHorizontalDragStart / onHorizontalDragUpdate callbacks together with onHorizontalDragEnd to get more data and determine swipe distance and direction.拥有GestureDetector ,您可以使用onHorizontalDragStart / onHorizontalDragUpdate回调和onHorizontalDragEnd来获取更多数据并确定滑动距离和方向。

However, depending on your task, it might be better to use more high-level widgets like PageView但是,根据您的任务,最好使用更高级别的小部件,例如PageView

You can detect swipes using the onPanUpdate method from GestureDetector class.您可以使用 GestureDetector class 中的onPanUpdate方法检测滑动。

GestureDetector(onPanUpdate: (details) {
  if (details.delta.dx > 0)
    print("Dragging in +X direction");
  else
    print("Dragging in -X direction");

  if (details.delta.dy > 0)
    print("Dragging in +Y direction");
  else
    print("Dragging in -Y direction");
});

Note: Do not use this method with the ones that you are already using (onVerticalDragDown) or onVerticalDragUpdate().注意:不要将此方法与您已经使用的方法 (onVerticalDragDown) 或 onVerticalDragUpdate() 一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM