You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何将SfCartesianChart的Trackball tooltip置于轨迹线顶部中央

在Flutter SfCartesianChart中实现Trackball Tooltip定位到轨迹线顶部中央

这个需求完全可以实现,通过配置TrackballBehavior的参数结合自定义tooltip构建器就能达到效果,具体操作如下:

核心配置步骤

  • 启用Trackball并设置水平居中对齐
    在TrackballBehavior中设置tooltipAlignment: ChartAlignment.center,让tooltip在水平方向上与轨迹线居中对齐。
  • 调整垂直偏移量
    使用tooltipOffset属性设置垂直方向的偏移,将tooltip向上移动到轨迹线顶部。数值需要根据你的tooltip实际高度调整,比如设置tooltipOffset: const Offset(0, -25)。
  • 自定义tooltip(可选,用于更精确控制)
    如果需要更精细的位置调整或自定义样式,使用tooltipBuilder,通过Transform.translate微调位置,同时自定义tooltip的外观。

示例代码

SfCartesianChart(
  trackballBehavior: TrackballBehavior(
    enable: true,
    tooltipAlignment: ChartAlignment.center,
    tooltipOffset: const Offset(0, -25),
    lineType: TrackballLineType.vertical,
    tooltipBuilder: (data, point, series, pointIndex, seriesIndex) {
      return Transform.translate(
        offset: const Offset(0, -10), // 额外微调垂直位置
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6),
            boxShadow: const [
              BoxShadow(color: Colors.black26, blurRadius: 3)
            ],
          ),
          child: Text(
            '数值: ${point.y}',
            style: const TextStyle(fontSize: 12),
          ),
        ),
      );
    },
  ),
  // 图表基础配置示例
  primaryXAxis: CategoryAxis(),
  series: <LineSeries<SalesData, String>>[
    LineSeries<SalesData, String>(
      dataSource: [
        SalesData('Jan', 35),
        SalesData('Feb', 28),
        SalesData('Mar', 34),
        SalesData('Apr', 32),
        SalesData('May', 40)
      ],
      xValueMapper: (SalesData sales, _) => sales.month,
      yValueMapper: (SalesData sales, _) => sales.sales,
    )
  ],
)

// 辅助数据类
class SalesData {
  SalesData(this.month, this.sales);
  final String month;
  final double sales;
}

注意事项

  • tooltipOffset的垂直偏移值需要根据tooltip的实际高度调整,确保tooltip底部刚好贴合轨迹线顶部。
  • 如果使用自定义tooltip builder,Transform.translate的偏移量可以根据需求进一步微调,实现更精准的定位。
  • 确保lineType设置为对应轨迹线类型(垂直/水平),匹配你的图表交互逻辑。

内容的提问来源于stack exchange,提问作者Srisha Deshpande

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 01:46:07