首页 > 解决方案 > CustomPainter 工具提示

问题描述

在 Flutter 中,我使用 aCustomPainter来渲染一个相对复杂的图表(带有点、注释、标签、轴等)。当用户将鼠标悬停在数据点上时(我正在使用 Flutter web),我想显示该点的工具提示。我正在尝试弄清楚如何编写此代码,以免影响性能(重新绘制图表很昂贵)。

主要问题是这样的:

每个点的位置都是在 的paint(..)方法内计算的CustomPainter

我将如何为我的 实施工具提示CustomPainter?大概我需要访问鼠标位置和每个点的位置以检查是否有任何相交。

我的第一个想法是在paint(..)完成后执行一个回调,返回点位置。然后第二个CustomPainter(覆盖在第一个上使用 aStack将接收点并检查与鼠标的碰撞(如有必要,渲染工具提示)。理论上,当鼠标位置onHover更新_x_y,只有_TooltipPainter应该重建(因为 Flutter 会检测到没有变化是对传递给ScatterPainter) 的 args 进行的。但是,在实践中,Flutter 会抛出错误“在帧期间计划构建。”。有什么想法吗?

return Stack(
  fit: StackFit.expand,
  children: [
    Container(
        child: MouseRegion(
            onHover: (event) {
              if (pointPositions.length > 0) {
                // Flutter should see that only _TooltipPainter needs to be rebuilt here.
                setState(() {
                  _x = event.localPosition.dx;
                  _y = event.localPosition.dy;
                });
              }
            },
            child: CustomPaint(painter: _TooltipPainter(pointPositions, _x, _y)))),
    RepaintBoundary(
        child: CustomPaint(
            painter: _ScatterPainter(widget.config, onPaintCompleted: (points) {
      // Executed once _ScatterPainter's paint(..) completes.
      // points is a List<Offset> containing the data points' draw locations
      setState(() {
        pointPositions = points;
      });
    })))
  ],
);

标签: flutter

解决方案


推荐阅读