Sub topic 9
Tracking Drags with Pan Callbacks
This chapter assumes you know basic Dart closures, Flutter widget trees, StatefulWidget, setState, and layout widgets such as Stack and Positioned.
A drag is a pointer movement that starts on a widget and continues while the pointer moves. GestureDetector recognizes this movement with pan callbacks. A pan can come from a mouse, finger, or stylus.
The pan callback sequence
A typical drag follows this sequence:
The callbacks provide different information:
| Callback | When it runs | Useful data |
|---|---|---|
| `onPanStart` | The drag is recognized | Starting position |
| `onPanUpdate` | The pointer moves | Movement since the last update |
| `onPanEnd` | The pointer is released | Final velocity |
| `onPanCancel` | The gesture is interrupted | Cleanup state |
The most useful value during a drag is DragUpdateDetails.delta. It is an Offset containing the horizontal and vertical movement since the previous update. Add this value to a stored position to make a widget follow the pointer.
Moving a widget with `onPanUpdate`
The following complete app places a square inside a Stack. The square follows the pointer and stays inside the available area.
import 'dart:math' as math;
import 'package:flutter/material.dart';
void main() {
runApp(const DragDemo());
}
class DragDemo extends StatefulWidget {
const DragDemo({super.key});
@override
State<DragDemo> createState() => _DragDemoState();
}
class _DragDemoState extends State<DragDemo> {
Offset _position = const Offset(40, 40);
bool _isDragging = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Pan demo')),
body: LayoutBuilder(
builder: (context, constraints) {
const boxSize = 96.0;
final maxX = math.max(0.0, constraints.maxWidth - boxSize);
final maxY = math.max(0.0, constraints.maxHeight - boxSize);
return Stack(
children: [
Positioned(
left: _position.dx,
top: _position.dy,
child: GestureDetector(
onPanStart: (_) {
setState(() => _isDragging = true);
},
onPanUpdate: (details) {
final next = _position + details.delta;
final bounded = Offset(
next.dx.clamp(0.0, maxX).toDouble(),
next.dy.clamp(0.0, maxY).toDouble(),
);
setState(() => _position = bounded);
},
onPanEnd: (_) {
setState(() => _isDragging = false);
},
onPanCancel: () {
setState(() => _isDragging = false);
},
child: DecoratedBox(
decoration: BoxDecoration(
color: _isDragging ? Colors.teal : Colors.indigo,
borderRadius: BorderRadius.circular(16),
),
child: const SizedBox(
width: boxSize,
height: boxSize,
child: Center(
child: Text(
'Drag',
style: TextStyle(color: Colors.white),
),
),
),
),
),
),
],
);
},
),
),
);
}
}setState is required because changing _position must rebuild the Positioned widget. The LayoutBuilder supplies the available size, which lets the example clamp the square to the screen boundaries.
onPanStart and onPanEnd update visual state. The underscore in onPanStart: (_), for example, means the callback receives details that this example does not need.
Common errors
- Replacing the position with
details.localPositioncan make the widget jump.localPositionis measured from the gesture detector, whiledeltarepresents movement since the previous event. - Forgetting
setStatechanges the field but leaves the screen unchanged. - Omitting
onPanCancelcan leave a “dragging” highlight active after another widget takes control. - Using a
Stackwithout bounds can let the dragged widget move outside the visible area. - Placing another gesture detector above or below this one can create competing recognizers. Flutter resolves those recognizers through its gesture arena.
Exercise
Why does the example add details.delta to position instead of assigning details.localPosition to position?
Show answer
details.delta is the movement since the previous update, so adding it produces smooth relative motion. localPosition is a coordinate inside the gesture detector and can cause a jump when the pointer starts away from the widget's origin.