Flutter- GestureDetector detect the direction of Horizontal and Vertical Drag

Viewed 19740

I am using GestureDetector and didn't find any onXYZ event which tells you the direction of drag.

2 Answers

Did you try onPanUpdate(details) method? Here is how you can do it.

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");
  },
  child: Container(
    color: Colors.blue,
    width: double.infinity,
    height: double.infinity,
  ),
)

Note: This callback causes a crash if onHorizontalDragUpdate() or onVerticalDragUpdate() is also provided as mentioned by anmol.majhail.

For those, who have "Having both a pan gesture recognizer and a scale gesture recognizer is redundant; scale is a superset of pan." error:

Implementing both drag and zoom-in with [onScaleUpdate] in [GestureDetector] widget:

onScaleUpdate: (scaleInfo) {
  //for drag, use [scaleInfo.focalPointDelta.dx] and [scaleInfo.focalPointDelta.dy]
  _controller.translate(scaleInfo.focalPointDelta.dx, scaleInfo.focalPointDelta.dy);
  
  //for zooming use [scaleInfo.scale] and don't react when zoom is exactly '1' [scaleInfo.scale != 1]
  if (scaleInfo.scale > 0.5 && scaleInfo.scale < 2 && scaleInfo.scale != 1) {
    setState(() {
      currentSize = Size(widget.size.width * scaleInfo.scale, widget.size.height * scaleInfo.scale);
    });
  }
},
Related