Infinite 2D Gallery
Build a custom, highly performant infinite 2D canvas with natural momentum scrolling and pinch-to-zoom physics.
Infinite 2D Gallery Engine 🗺️
Sometimes GridView and InteractiveViewer just aren’t enough when you want to build a truly unbounded canvas (like a map or an infinite photo grid) that feels completely native and handles natural scrolling momentum.
In this advanced tutorial, we build a Custom 2D Scrolling Engine from scratch, featuring a staggered honeycomb layout!
1. Natural Momentum Physics
To simulate realistic scrolling (flinging), we capture the velocity when the user lifts their finger in onScaleEnd. We then calculate a stopping distance and animate our offset using a curved animation (Curves.easeOutCubic) to mimic friction!
void _onScaleEnd(ScaleEndDetails details) {
final velocity = details.velocity.pixelsPerSecond;
final distance = velocity.distance * 0.15;
if (distance > 10) {
final direction = velocity / velocity.distance;
final endOffset = _offset + (direction * distance);
_animation = Tween<Offset>(begin: _offset, end: endOffset).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeOutCubic)
);
_controller.forward(from: 0);
}
}
2. Pinch-to-Zoom centered on the Fingers
When scaling, if we simply multiply our items by _scale, the zoom will center on the top-left of the screen. To make it zoom exactly where the user is pinching (the focal point), we apply this vector math trick:
final newScale = (_baseScale * details.scale).clamp(0.3, 3.0);
final scaleRatio = newScale / _scale;
// Keep the focal point locked by shifting the offset
_offset = details.localFocalPoint - (details.localFocalPoint - _offset) * scaleRatio;
_scale = newScale;
3. The Staggered Math (Honeycomb Layout)
To make the gallery look organic rather than a rigid chess board, we shift every odd column downwards by exactly half a tile size (tileSize / 2).
// If the column index is an odd number, push the tile down by half its height
final double staggeredOffsetY = (col.abs() % 2 == 1) ? (tileSize / 2) : 0.0;
final double x = col * tileSize + _offset.dx;
final double y = row * tileSize + _offset.dy + staggeredOffsetY;
4. High Performance Rendering
A truly infinite grid would crash the app if we rendered every item. Instead, we calculate exactly how many columns and rows fit on the screen based on the current scale, and only generate the Positioned widgets for the visible tiles. This makes the gallery incredibly smooth, even if it spans millions of theoretical pixels!