'How to detect left and right swipes in flutter?

I am using GestureDetector to check when a user swipes horizontally across the screen.

The swipe should only be registered when the user removes their finger from the screen to end the swipe, hence the use of onHorizontalDragEnd.

When the swipe ends a int is incremented resulting in a new image being displayed.

The issue I am having is that I want to be able to let the user swipe left to go back an image.

How can I detect which direction a user has swiped when implementing onHorizontalDragEnd?



Solution 1:[1]

You can detect swipes using the onPanUpdate method from GestureDetector class.

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().

Solution 2:[2]

Having GestureDetector, you can use onHorizontalDragStart/onHorizontalDragUpdate callbacks together with onHorizontalDragEnd to get more data and determine swipe distance and direction.

However, depending on your task, it might be better to use more high-level widgets like PageView

Solution 3:[3]

Use GestureDetector. Example

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yudhishthir Singh
Solution 2 Pavel
Solution 3 Shahriar Nasim Nafi