Sub topic 10
Pinch and rotate with scale callbacks
This chapter covers onScaleStart, onScaleUpdate and onScaleEnd on GestureDetector. It assumes you know setState, StatefulWidget, and the pan callbacks from the previous chapter on drags. It also assumes you have a rough idea of what Transform does.
What the scale gesture reports
The scale recognizer tracks the pointers (fingers) that are touching its widget and reports three values that change as they move:
- Scale: how far the fingers have moved apart or together, as a ratio.
- Rotation: how far the line between the fingers has turned, in radians.
- Focal point: the average position of all the fingers.
The name is slightly misleading. It also handles one-finger movement, which is why it replaces pan callbacks whenever you need more than a drag.
Each callback receives a details object.
| Callback | Details type | Useful fields |
|---|---|---|
| `onScaleStart` | `ScaleStartDetails` | `focalPoint`, `localFocalPoint`, `pointerCount` |
| `onScaleUpdate` | `ScaleUpdateDetails` | `scale`, `horizontalScale`, `verticalScale`, `rotation`, `focalPoint`, `localFocalPoint`, `focalPointDelta`, `pointerCount` |
| `onScaleEnd` | `ScaleEndDetails` | `velocity`, `pointerCount` |
The focalPoint fields are in global (screen) coordinates. The localFocalPoint fields are relative to the widget that owns the detector.
Values are relative to the gesture start
The most common mistake with scale gestures is treating details.scale as the widget's current scale. It is not. At the start of every gesture, scale is 1.0 and rotation is 0.0. During the gesture they report the change since that start.
If your widget is already at 2x and the user starts a new pinch, details.scale begins at 1.0 again. If you assign it directly, the widget snaps back to 1x. The fix has three steps:
- In
onScaleStart, copy the current scale and rotation into "base" fields. - In
onScaleUpdate, computebase * details.scalefor scale, andbase + details.rotationfor rotation. - Optionally clamp the result.
Rotation is additive because angles add. Scale is multiplicative because ratios multiply.
A complete pinch, rotate and move example
This widget fills the screen and shows a square you can pinch, twist and drag. It displays its current scale as text so the behavior is easy to see, and so a test can read it later.
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(body: PinchRotateBox()),
),
);
}
class PinchRotateBox extends StatefulWidget {
const PinchRotateBox({super.key});
@override
State<PinchRotateBox> createState() => _PinchRotateBoxState();
}
class _PinchRotateBoxState extends State<PinchRotateBox> {
Offset _offset = Offset.zero;
double _scale = 1.0;
double _rotation = 0.0;
double _baseScale = 1.0;
double _baseRotation = 0.0;
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onScaleStart: (details) {
_baseScale = _scale;
_baseRotation = _rotation;
},
onScaleUpdate: (details) {
setState(() {
_scale = (_baseScale * details.scale).clamp(0.5, 4.0).toDouble();
_rotation = _baseRotation + details.rotation;
_offset += details.focalPointDelta;
});
},
child: SizedBox.expand(
child: Center(
child: Transform.translate(
offset: _offset,
child: Transform.rotate(
angle: _rotation,
child: Transform.scale(
scale: _scale,
child: Container(
width: 120,
height: 120,
color: Colors.teal,
alignment: Alignment.center,
child: Text(
'scale ${_scale.toStringAsFixed(2)}',
style: const TextStyle(color: Colors.white),
),
),
),
),
),
),
),
);
}
}Some details in this code are worth noting:
- The detector wraps a
SizedBox.expandand usesHitTestBehavior.opaque. This lets a pinch start anywhere on screen, not only on the square. If the detector wrapped only the transformed square, a small square would be hard to grab. - Movement uses
focalPointDelta, the change in focal point since the previous update. Adding it to_offsetgives a drag with one finger and a drag of the midpoint with two. clampon adoubleis typed asnum, so.toDouble()converts it back.- The base values are plain fields, not state. Changing them does not need
setState, because nothing is drawn from them.
Scale replaces pan, and the two cannot be combined
The scale recognizer is a superset of pan. A GestureDetector that sets both onPan* and onScale* fails an assertion in debug mode. The message says that having both recognizers is redundant, because scale already covers pan.
For one finger, scale stays at 1.0 and rotation stays at 0.0. Your update code therefore works unchanged for single-finger dragging.
Pointer count changes and the scale baseline
Fingers rarely land or lift at exactly the same moment. When the number of pointers changes during a gesture, the recognizer recomputes its reference values, so the gesture's baseline restarts and scale returns to 1.0. This is why capturing base values in onScaleStart and reading pointerCount are both worth doing. Do not write code that assumes exactly one start and one end per physical touch. Write it so that every start captures a fresh baseline and every update applies a delta to that baseline.
Some practical consequences:
- To react only to real pinches, check
details.pointerCount >= 2inonScaleUpdate. - If a rotation feels jumpy when a second finger lands, the cause is usually a baseline captured in the wrong place, such as in
initState. horizontalScaleandverticalScalegive non-uniform stretch. Use them if you resize a box along one axis. For uniform zoom, usescale.
Using the velocity in onScaleEnd
ScaleEndDetails.velocity contains the pixel-per-second velocity of the focal point when the fingers lift. You can use it to build fling behavior with an AnimationController and a Tween<Offset>. The velocity is zero if the fingers stopped before lifting. Check pointerCount too: when one finger of two lifts, onScaleEnd can report pointerCount of 1 while a finger is still down.
Zooming around the focal point
The example above scales around the center of the square, not around the point between the user's fingers. Pinch zoom in maps and photo viewers feels natural because the content under the fingers stays under the fingers. Achieving that requires a Matrix4 that translates to the focal point, scales, and translates back, and it needs more bookkeeping for rotation.
Before you write that, consider InteractiveViewer. It is a built-in widget that wraps a child and handles pan, pinch zoom, optional rotation and fling, with minScale, maxScale and a TransformationController. Use raw scale callbacks when you need custom behavior, such as snapping, a rotation handle, or a game-like canvas. Use InteractiveViewer when you only need to let the user inspect content.
Testing a pinch
WidgetTester.tap and drag use a single pointer, so they cannot test a pinch. Start two gestures with startGesture instead. This test uses the PinchRotateBox above and checks that the label changed.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('spreading two fingers increases the scale', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: PinchRotateBox())),
);
expect(find.text('scale 1.00'), findsOneWidget);
final center = tester.getCenter(find.byType(PinchRotateBox));
final first = await tester.startGesture(center - const Offset(20, 0));
final second = await tester.startGesture(center + const Offset(20, 0));
await first.moveBy(const Offset(-40, 0));
await second.moveBy(const Offset(40, 0));
await tester.pump();
await first.up();
await second.up();
await tester.pump();
expect(find.text('scale 1.00'), findsNothing);
});
}The fingers move farther than the recognizer's slop distance, which is the small movement that must happen before the gesture wins. A move of a few pixels would never trigger it, and the test would wrongly fail. Asserting that the text is no longer scale 1.00 avoids depending on exact floating-point results.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Widget snaps to 1x at the start of each pinch | `details.scale` assigned directly | Multiply by a base scale saved in `onScaleStart` |
| Assertion about pan and scale | Both callback sets on one detector | Remove the pan callbacks and use `focalPointDelta` |
| Pinch only works on the square | Detector wraps only the small child | Wrap a full-size area with `HitTestBehavior.opaque` |
| Rotation looks wrong by a large factor | Treating radians as degrees | Convert with `radians * 180 / math.pi` for display only |
| Test never triggers scale | Single-pointer `drag` or movement under the slop | Use two `startGesture` pointers and move 20 or more pixels |
Exercise
A user pinches your widget to 2x, lifts both fingers, then pinches again by a factor of 1.5. What should the final scale be, and which two lines make that work?
Show answer
The final scale should be 3.0, since 2.0 x 1.5. In onScaleStart, save _baseScale = _scale;. In onScaleUpdate, set _scale = _baseScale * details.scale;. Without the base value, the second pinch would start from 1.0 and end at 1.5.
Exercise
Your detector sets both onPanUpdate and onScaleUpdate, and the app throws an assertion in debug mode. How do you keep one-finger dragging while supporting pinch?
Show answer
Remove the onPan callbacks and use only the onScale callbacks. For one-finger movement, add details.focalPointDelta to the stored offset in onScaleUpdate. With one finger, scale stays 1.0 and rotation stays 0.0, so the same code handles both cases.