Sub topic 9
Tracking drags with pan callbacks
A drag moves a widget, scrolls a canvas, or draws a line under the user's finger. This chapter covers GestureDetector's pan callbacks, which report free movement in both axes. You will build a draggable box that stays inside its container, and you will see what each callback receives and where drags fail.
This chapter assumes you can write a StatefulWidget, call setState, and lay out children with Stack and Positioned. It also assumes you know the tap callbacks from the earlier GestureDetector chapter.
The five pan callbacks
A pan is a drag in any direction. GestureDetector exposes five callbacks for it:
| Callback | When it fires | Argument |
|---|---|---|
| `onPanDown` | The pointer touches the widget. A drag is possible but not yet confirmed. | `DragDownDetails` |
| `onPanStart` | The pointer has moved far enough that Flutter accepts the drag. | `DragStartDetails` |
| `onPanUpdate` | The pointer moved after the drag started. | `DragUpdateDetails` |
| `onPanEnd` | The pointer lifted after a drag. | `DragEndDetails` |
| `onPanCancel` | The pointer went down but the drag never completed. | none |
The order matters. A touch that only taps produces onPanDown and then onPanCancel, because the tap recognizer wins and the pan recognizer loses. A real drag produces onPanDown, onPanStart, any number of onPanUpdate calls, and onPanEnd.
Touch slop
Flutter does not start a drag on the first pixel of movement. A finger always wobbles slightly, so the recognizer waits until the pointer has moved a minimum distance, called the slop. For a touch pan this is about 36 logical pixels. Until then, other recognizers such as tap can still win.
By default (DragStartBehavior.start), the slop distance is not counted in the first onPanUpdate. The drag begins where the slop was crossed, so the widget does not jump. If you set dragStartBehavior: DragStartBehavior.down, the movement since the pointer went down is included, and the first update can be a larger jump.
What the details objects contain
onPanUpdate is the callback you will use most. Its DragUpdateDetails has these fields:
deltais the movement since the previous update, as anOffsetin logical pixels.globalPositionis the pointer position in screen coordinates.localPositionis the pointer position relative to the detector's own box.primaryDeltaisnullfor pan gestures. It is set only by horizontal and vertical drag callbacks, where one axis is "primary".
DragStartDetails carries globalPosition and localPosition. DragEndDetails carries velocity, whose pixelsPerSecond is an Offset. You use it to turn a release into a fling.
Prefer delta over computing differences from globalPosition yourself. The delta is already measured between two consecutive events, so adding it to stored state keeps the widget under the finger.
A draggable box
This example moves a box with onPanUpdate. It adds a pressed color and keeps the box inside its parent. The program is complete and can be run as shown.
import 'dart:math' as math;
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: DraggableBox())));
}
class DraggableBox extends StatefulWidget {
const DraggableBox({super.key});
@override
State<DraggableBox> createState() => _DraggableBoxState();
}
class _DraggableBoxState extends State<DraggableBox> {
static const double _size = 80;
Offset _position = const Offset(40, 40);
bool _dragging = false;
void _endDrag() => setState(() => _dragging = false);
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final maxX = math.max(0.0, constraints.maxWidth - _size);
final maxY = math.max(0.0, constraints.maxHeight - _size);
return Stack(
children: [
Positioned(
left: _position.dx,
top: _position.dy,
child: GestureDetector(
onPanStart: (_) => setState(() => _dragging = true),
onPanUpdate: (details) {
final next = _position + details.delta;
setState(() {
_position = Offset(
next.dx.clamp(0.0, maxX).toDouble(),
next.dy.clamp(0.0, maxY).toDouble(),
);
});
},
onPanEnd: (_) => _endDrag(),
onPanCancel: _endDrag,
child: Container(
width: _size,
height: _size,
color: _dragging ? Colors.deepPurple : Colors.indigo,
),
),
),
],
);
},
);
}
}Four details in this code are easy to get wrong.
- The state holds the position, and
setStaterebuildsPositionedwith the newleftandtop. The gesture callback never moves the widget directly. LayoutBuildersupplies the available size, so the clamp bounds adapt to the screen.math.max(0.0, ...)prevents a negative upper bound, becauseclampthrows if the lower bound exceeds the upper one.clampreturnsnum, so.toDouble()is needed to build anOffset.onPanEndandonPanCancelboth reset_dragging. If you handle onlyonPanEnd, an interrupted drag leaves the box stuck in its pressed color.
Using the end velocity
onPanEnd tells you how fast the finger was moving when it lifted. A common use is to decide whether a quick flick should trigger an action:
GestureDetector(
onPanEnd: (details) {
final speed = details.velocity.pixelsPerSecond.distance;
if (speed > 800) {
debugPrint('fling at $speed px/s');
} else {
debugPrint('slow release');
}
},
child: const SizedBox(width: 200, height: 200),
)Offset.distance is the length of the vector, so speed ignores direction. Use pixelsPerSecond.dx or .dy when direction matters. The threshold is a tuning value: the Flutter framework uses 50 pixels per second as a minimum fling velocity for scrolling, so values in the hundreds mean a deliberate flick.
Common problems
The detector has no area to hit. A GestureDetector with no child, or with a transparent child, does not receive events in empty regions. Give it a sized child, or set behavior: HitTestBehavior.opaque. The hit testing chapter explains why.
Pan and scale in the same detector. You cannot register both onPan* and onScale* on one GestureDetector. Flutter fails an assertion in debug mode, because scale recognizes one-finger drags too. Use the scale callbacks and read focalPointDelta instead.
Pan inside a scrollable. A pan detector inside a ListView competes with the list's own vertical drag recognizer. Which one wins depends on the gesture arena, covered in a later chapter. If you only need movement along one axis, use onHorizontalDragUpdate or onVerticalDragUpdate. They compete less often with a scrollable that scrolls the other way.
Rebuilding the whole tree on every update. onPanUpdate can fire on every frame, and each call here runs setState. Keep the State object small and put the moving part in its own widget so only that subtree rebuilds. For heavier cases, an AnimatedBuilder or ValueNotifier limits rebuilds further.
Using the wrong coordinate space. globalPosition is relative to the screen, and localPosition is relative to the detector. Inside a Stack with Positioned, mixing them produces an offset equal to the widget's own origin. Pick one space and stay in it.
Summary of decisions
- Use
onPanUpdateanddetails.deltafor free two-axis movement. - Reset any "pressed" state in both
onPanEndandonPanCancel. - Clamp inside the same
setStatethat writes the position, and size the bounds fromLayoutBuilder. - Use
onPanEndvelocity for fling decisions. - Use horizontal or vertical drag callbacks when only one axis matters, and scale callbacks when you also need pinch or rotation.
Exercise
In the draggable box example, you remove the onPanCancel handler. A user touches the box, starts dragging, and then an incoming system gesture interrupts the drag. What does the user see afterward, and why?
Show answer
The box stays in the pressed color (Colors.deepPurple). onPanStart set _dragging to true, and an interrupted drag calls onPanCancel instead of onPanEnd. With no onPanCancel handler, nothing resets _dragging to false.
Exercise
A pan detector wraps a 100 by 100 box. You drag 20 logical pixels to the right with a touch, which is below the touch pan slop. Which callbacks have fired by the time you lift your finger, and does the box move?
Show answer
Only onPanDown and onPanCancel fire. The movement never passes the slop distance, so onPanStart and onPanUpdate never run, and the box does not move.
Exercise
Why is details.primaryDelta null inside onPanUpdate, and which callbacks would give you a non-null value?
Show answer
A pan has no single primary axis, so Flutter leaves primaryDelta null. It is set in onHorizontalDragUpdate (the horizontal movement) and onVerticalDragUpdate (the vertical movement).