使用fl_chart时如何添加代表当前时间的红色now标记线?
实现方案
你可以通过LineChartData自带的extraLinesData属性配置垂直辅助线实现需求,步骤如下:
- 第一步:计算当前时间对应的X轴坐标值
currentTimeX:根据你自己的日期映射逻辑,把当前时间转换为和现有X轴刻度匹配的数值即可,比如你的X轴是dates数组的索引,就找到当前时间在dates数组中对应的位置作为currentTimeX。 - 第二步:在原有
LineChartData配置中新增extraLinesData属性,添加红色垂直竖线,还可以按需配置虚线、文字标注等效果。
修改后的完整代码如下:
LineChartData( maxY: maxY + 10 * _onePercentRange, minY: minY - 10 * _onePercentRange, // 新增额外线配置 extraLinesData: ExtraLinesData( verticalLines: [ VerticalLine( x: currentTimeX, // 替换为你计算出的当前时间X轴坐标 color: Colors.red, strokeWidth: 2, // 可选配置:添加虚线效果 dashArray: [5, 3], // 可选配置:线上添加"NOW"文字标注 label: VerticalLineLabel( label: "NOW", alignment: Alignment.topRight, style: TextStyle( color: Colors.red, fontSize: 12, fontWeight: FontWeight.bold, ), padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2), ), ), ], ), titlesData: FlTitlesData( bottomTitles: SideTitles( showTitles: true, margin: 10, getTitles: (value) { return getDateBaseInFormatFromJsonString( dates[value.toInt()], "MM/dd\nHHmm"); }, ), ), borderData: FlBorderData( show: true, border: Border( bottom: BorderSide( color: currentTheme.primaryColor, width: 2, ), left: BorderSide( color: currentTheme.primaryColor, width: 2, ), ), ), lineBarsData: [ LineChartBarData( spots: spots, isCurved: true, colors: [currentTheme.primaryColor], isStrokeCapRound: true, dotData: FlDotData( show: false, ), ), ], );
如果使用的是旧版本fl_chart,注意VerticalLineLabel的属性名可能存在细微差异,按需调整即可。
内容的提问来源于stack exchange,提问作者Erick Lanford Xenes
相关产品推荐
相关产品推荐

