在Flutter的fl_chart(0.59.0)中如何添加水平Tooltip?
fl_chart 0.59.0 实现水平Tooltip的解决方案
要实现显示y轴数值的水平Tooltip(比如你提到的“3.74%”),可以通过两种方式实现,以下是具体方案:
方案一:自定义固定位置的水平Tooltip(推荐)
这种方式可以完全控制Tooltip的位置和样式,适合需要将数值固定在y轴侧边的场景:
- 在页面State类中添加状态变量,记录触摸状态和Tooltip信息:
String? _currentYValue; bool _showHorizontalTooltip = false; Offset? _tooltipOffset;
- 修改
LineTouchData配置,关闭内置触摸处理,改用自定义触摸回调:
LineTouchData( handleBuiltInTouches: false, touchCallback: (FlTouchEvent event, LineTouchResponse? response) { // 处理触摸结束事件,隐藏Tooltip if (event is FlTapUpEvent || event is FlPanEndEvent) { setState(() { _showHorizontalTooltip = false; _currentYValue = null; }); return; } // 处理触摸开始/移动事件,更新Tooltip内容和位置 if (response?.lineBarSpots != null && response!.lineBarSpots!.isNotEmpty) { final spot = response.lineBarSpots!.first; setState(() { _currentYValue = '${spot.y.toStringAsFixed(2)}%'; // 格式化y值为百分比 _showHorizontalTooltip = true; // 计算Tooltip位置,这里固定在图表右侧,可根据需求调整 _tooltipOffset = Offset( MediaQuery.of(context).size.width - 80, spot.yAxisPosition - 15, // 垂直居中偏移 ); }); } }, // 保留你原来的触摸点指示器配置 getTouchedSpotIndicator: (barData, spotIndexes) => spotIndexes .map( (e) => TouchedSpotIndicatorData( const FlLine(color: Colors.red, strokeWidth: 1.5, dashArray: [2, 2]), FlDotData( getDotPainter: (p0, p1, p2, p3) => FlDotCirclePainter( radius: 3.5, color: Colors.white, strokeWidth: 2.0, strokeColor: Colors.red), )), ).toList(), )
- 用
Stack包裹LineChart,添加自定义Tooltip组件:
Stack( children: [ LineChart( LineChartData( // 你的其他图表配置... lineTouchData: // 上面修改后的LineTouchData ), ), // 显示水平Tooltip if (_showHorizontalTooltip && _currentYValue != null && _tooltipOffset != null) Positioned( left: _tooltipOffset!.dx, top: _tooltipOffset!.y, child: Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(1.5), ), child: Text( _currentYValue!, style: const TextStyle( color: Colors.white, fontSize: 10.0, fontWeight: FontWeight.bold, ), ), ), ), ], )
方案二:扩展内置Tooltip同时显示x/y值
如果不需要固定位置,只是想在同一个Tooltip里同时显示日期和数值,直接修改getTooltipItems即可:
touchTooltipData: LineTouchTooltipData( // 保留你原来的Tooltip样式配置... getTooltipItems: (touchedSpots) => touchedSpots .map( (e) { final xText = widget.data.xSeries == null ? '' : widget.data.xSeries![e.spotIndex]; final yText = '${e.y.toStringAsFixed(2)}%'; return LineTooltipItem( '$xText\n$yText', const TextStyle( color: Colors.white, fontSize: 10.0, fontWeight: FontWeight.bold, ), ); }, ).toList(), ),
内容的提问来源于stack exchange,提问作者Jerry
相关产品推荐
相关产品推荐

