How to properly handle offsets with Flutter GestureDetector and InteractiveViewer

Problem

I am building a Widget that draws objects where I would like to allow panning+zooming while also detecting when taps/clicks overlap with objects drawn on the screen.

The problem is that after panning or zooming, the taps are registered local to the initial frame, causing a significat offset to the actual cursor position, and making it impossible to tap on anything that is outside the original frame.

Debug screenshots

Before zoom

In the screenshots, I’ve but a green box around the initial frame and a red dot where the cursor tap is being registered. Note that before zooming everything is as expected and the the tap on the cirlce is detected (you can see the “Node tapped” in terminal output).

After zoom

After zoom the tap position looks to be local to the orginal (zoomed-out) frame, is totally offset from the cursor, and the circle under the cursor is not detected as a hit. In fact it can never be hit because it’s outside the green box representing the original draw frame.

Code

import 'package:flutter/material.dart';
import 'dart:math';

class GraphWidget extends StatefulWidget {
  @override
  _GraphWidgetState createState() => _GraphWidgetState();
}

class _GraphWidgetState extends State<GraphWidget> {
  List<Offset> nodes = [];
  EdgeInsets boundaryMargin = EdgeInsets.all(20.0);
  Offset? tapPosition;

  @override
  void initState() {
    super.initState();
    _generateRandomNodes();
  }

  void _generateRandomNodes() {
    final random = Random();
    nodes = List.generate(10, (index) {
      return Offset(
        random.nextDouble() * 2000,
        random.nextDouble() * 2000,
      );
    });

    setState(() {
      _calculateBoundaryMargin();
    });
  }

  void _calculateBoundaryMargin() {
    if (nodes.isEmpty) {
      return;
    }

    double minX = nodes.map((node) => node.dx).reduce((a, b) => a < b ? a : b);
    double maxX = nodes.map((node) => node.dx).reduce((a, b) => a > b ? a : b);
    double minY = nodes.map((node) => node.dy).reduce((a, b) => a < b ? a : b);
    double maxY = nodes.map((node) => node.dy).reduce((a, b) => a > b ? a : b);

    double marginX = (maxX - minX) / 2;
    double marginY = (maxY - minY) / 2;

    setState(() {
      boundaryMargin = EdgeInsets.only(
        left: -minX + marginX,
        right: maxX + marginX,
        top: -minY + marginY,
        bottom: maxY + marginY,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Graph'),
      ),
      body: LayoutBuilder(
        builder: (context, constraints) {
          return GestureDetector(
            onTapUp: (details) {
              final RenderBox box = context.findRenderObject() as RenderBox;
              final Offset localOffset = box.globalToLocal(details.globalPosition);
              setState(() {
                tapPosition = localOffset;
              });
              _onCanvasTap(localOffset);
            },
            child: Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.red),
              ),
              child: InteractiveViewer(
                clipBehavior: Clip.none,
                boundaryMargin: boundaryMargin,
                minScale: 0.1,
                maxScale: 4.0,

                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.green),
                  ),
                  width: constraints.maxWidth * 2,
                  height: constraints.maxHeight * 2,

                  child: CustomPaint(
                    size: Size(constraints.maxWidth * 2, constraints.maxHeight * 2),
                    painter: GraphPainter(
                      nodes,
                      tapPosition: tapPosition,
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  void _onCanvasTap(Offset position) {
    print(position);
    for (final node in nodes) {
      if ((position - node).distance <= 20) {
        print('Node tapped at $node');
        break;
      }
    }
  }
}

class GraphPainter extends CustomPainter {
  final List<Offset> nodes;
  final Offset? tapPosition;

  GraphPainter(this.nodes, {this.tapPosition});

  @override
  void paint(Canvas canvas, Size size) {
    final nodePaint = Paint()
      ..color = Colors.green
      ..style = PaintingStyle.fill;

    for (final node in nodes) {
      canvas.drawCircle(node, 100, nodePaint);
    }

    if (tapPosition != null) {
      final tapPaint = Paint()
        ..color = Colors.red
        ..style = PaintingStyle.fill;
      canvas.drawCircle(tapPosition!, 15, tapPaint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

void main() {
  runApp(MaterialApp(
    home: GraphWidget(),
  ));
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật