← Back to posts Cover image for Mastering Performance: Achieving Smooth CAD-like Experiences in Flutter

Mastering Performance: Achieving Smooth CAD-like Experiences in Flutter

· 4 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

The bottleneck is rarely “drawing”

CAD-like Flutter apps usually feel slow for three reasons:

  1. The whole widget tree rebuilds during pan/zoom.
  2. Every frame paints entities that are off-screen.
  3. Hit testing scans hundreds or thousands of shapes.

The fix is to treat the app as a small graphics engine: keep geometry in world coordinates, use a viewport matrix, repaint only what changed, and make hit testing spatial.

Keep the viewport as a matrix

Do not store “zoom” and “pan” separately if you can avoid it. A Matrix4 gives you consistent screen-to-world and world-to-screen transforms.

class ViewportController extends ChangeNotifier {
  Matrix4 matrix = Matrix4.identity();

  void pan(Offset delta) {
    final translation = Matrix4.translationValues(delta.dx, delta.dy, 0);
    matrix = translation * matrix;
    notifyListeners();
  }

  void zoomAt(Offset local, double factor) {
    final to = Matrix4.translationValues(local.dx, local.dy, 0);
    final back = Matrix4.translationValues(-local.dx, -local.dy, 0);
    final scale = Matrix4.diagonal3Values(factor, factor, 1);

    matrix = to * scale * back * matrix;
    notifyListeners();
  }

  Rect visibleWorldRect(Size screen) {
    final inverse = matrix.clone()..invert();

    final topLeft = MatrixUtils.transformPoint(inverse, Offset.zero);
    final bottomRight = MatrixUtils.transformPoint(
      inverse,
      Offset(screen.width, screen.height),
    );

    return Rect.fromLTRB(
      topLeft.dx,
      topLeft.dy,
      bottomRight.dx,
      bottomRight.dy,
    ).inflate(64);
  }
}

For pan/zoom-only apps, the two-corner viewport rect is enough. If you add rotation, transform all four screen corners instead.

Paint one canvas, not a widget forest

A CAD drawing with hundreds of entities should not become hundreds of Containers or CustomPaints. Use one CustomPainter and cull by visible bounds.

class Shape {
  final Path path;
  final Paint paint;
  final Rect bounds;

  Shape(this.path, this.paint, this.bounds);

  void paintTo(Canvas canvas) => canvas.drawPath(path, paint);
  bool contains(Offset point) => path.contains(point);
}

class DrawingModel extends ChangeNotifier {
  final List<Shape> shapes = [];
  Shape? selection;

  void add(Shape shape) {
    shapes.add(shape);
    notifyListeners();
  }

  void select(Shape? shape) {
    if (selection != shape) {
      selection = shape;
      notifyListeners();
    }
  }
}

class DrawingPainter extends CustomPainter {
  final ViewportController viewport;
  final DrawingModel model;

  DrawingPainter(this.viewport, this.model)
      : super(repaint: Listenable.merge([viewport, model]));

  @override
  void paint(Canvas canvas, Size size) {
    canvas.save();
    canvas.transform(viewport.matrix.storage);

    final visible = viewport.visibleWorldRect(size);

    for (final shape in model.shapes) {
      if (shape.bounds.overlaps(visible)) {
        shape.paintTo(canvas);
      }
    }

    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant DrawingPainter oldDelegate) =>
      oldDelegate.viewport != viewport || oldDelegate.model != model;
}

RepaintBoundary around the canvas is important too. It keeps overlays, toolbars, and status indicators from forcing the drawing surface to repaint.

Hit testing should not be O(n)

When the user taps, do not loop through every shape. Use a coarse spatial index first, then precise geometry only on likely candidates.

class GridIndex {
  static const double cellSize = 256;
  final Map<int, List<Shape>> _buckets = {};

  int _key(int x, int y) => Object.hash(x, y);

  void insert(Shape shape) {
    final x0 = (shape.bounds.left / cellSize).floor();
    final x1 = (shape.bounds.right / cellSize).floor();
    final y0 = (shape.bounds.top / cellSize).floor();
    final y1 = (shape.bounds.bottom / cellSize).floor();

    for (var x = x0; x <= x1; x++) {
      for (var y = y0; y <= y1; y++) {
        _buckets.putIfAbsent(_key(x, y), () => <Shape>[]).add(shape);
      }
    }
  }

  Shape? hitTest(Offset worldPoint) {
    final x = (worldPoint.dx / cellSize).floor();
    final y = (worldPoint.dy / cellSize).floor();

    for (final shape in _buckets[_key(x, y)] ?? const <Shape>[]) {
      if (shape.bounds.contains(worldPoint) && shape.contains(worldPoint)) {
        return shape;
      }
    }

    return null;
  }
}

For very dense drawings, replace the uniform grid with a quadtree or R-tree. The key idea is the same: reduce candidate shapes before doing expensive path math.

Wire gestures without rebuilding everything

class DrawingView extends StatefulWidget {
  const DrawingView({
    super.key,
    required this.viewport,
    required this.model,
    required this.index,
  });

  final ViewportController viewport;
  final DrawingModel model;
  final GridIndex index;

  @override
  State<DrawingView> createState() => _DrawingViewState();
}

class _DrawingViewState extends State<DrawingView> {
  double _lastScale = 1.0;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (event) => widget.viewport.pan(event.delta),
      onScaleStart: (_) => _lastScale = 1.0,
      onScaleUpdate: (event) {
        final factor = event.scale / _lastScale;
        if (factor != 1.0) {
          _lastScale = event.scale;
          widget.viewport.zoomAt(event.localFocalPoint, factor);
        }
      },
      onTapUp: (event) {
        final inverse = widget.viewport.matrix.clone()..invert();
        final worldPoint = MatrixUtils.transformPoint(
          inverse,
          event.localPosition,
        );

        widget.model.select(widget.index.hitTest(worldPoint));
      },
      child: RepaintBoundary(
        child: CustomPaint(
          painter: DrawingPainter(widget.viewport, widget.model),
          size: Size.infinite,
        ),
      ),
    );
  }
}

Common mistakes

  • Calling setState on every pan/zoom frame.
  • Rebuilding the entire drawing widget tree for viewport changes.
  • Painting all shapes instead of only visible ones.
  • Using Stack with hundreds of positioned widgets for geometry.
  • Running Path.contains on every shape for every tap.
  • Forgetting RepaintBoundary around the main canvas.
  • Letting the UI layer own the transform instead of the painter.

A smooth Flutter CAD experience comes from discipline: one viewport matrix, one painted surface, spatial indexing for interaction, and repaints triggered only by actual model or camera changes.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.