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

Fl_charts BarChart标题切换异常问题求助

解决Fl Charts柱状图底部标题全部进入default分支的问题

问题根源

你在生成BarChartGroupData时,把x属性固定设置为barChartX.length(当前值为10),而getTitles方法接收的value就是这个x值。你的switch只处理了0-9的情况,10不在范围内,所以所有标题都进入default分支。

修复代码

只需要把BarChartGroupData的x值改成列表生成时的索引i即可,List.generate的第二个参数(i)就是当前迭代的索引,范围正好是0到barChartX.length-1(也就是0-9):

Expanded(
  child: Padding(
    padding: const EdgeInsets.all(8.0),
    child: BarChart(
      BarChartData(
        barTouchData: BarTouchData(
          touchTooltipData: BarTouchTooltipData(),
        ),
        alignment: BarChartAlignment.center,
        barGroups: List.generate(
          barChartX.length,
          // 把x的值从barChartX.length改成i
          (i) => BarChartGroupData(
            x: i, // 这里是关键修改
            barRods: [
              BarChartRodData(
                toY: relBarChart[i] * 10,
                color: Color.fromARGB(198, 74, 78, 74),
                width: 10.0,
                borderRadius: BorderRadius.circular(10),
                backDrawRodData: BackgroundBarChartRodData(
                  show: true,
                  color: Colors.grey,
                ),
              ),
            ],
          ),
        ),
        titlesData: FlTitlesData(
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
                getTitlesWidget: getTitles,
                showTitles: true,
                reservedSize: 38),
          ),
        ),
      ),
    ),
  ),
),

额外优化建议

你当前的getTitles方法用了冗长的switch语句,可以改成用列表存储标题,代码更简洁易维护:

Widget getTitles(double value, TitleMeta meta) {
  const style = TextStyle(
    color: Colors.red,
    fontWeight: FontWeight.bold,
    fontSize: 14,
  );
  // 定义标题列表,索引对应x值
  const titles = ['M', 'T', 'W', 'T', 'F', 'S', 'S', 'F', 'S', 'S'];
  int index = value.toInt();
  // 索引合法就取对应标题,否则显示default
  String text = index >=0 && index < titles.length ? titles[index] : 'default';
  return SideTitleWidget(
    axisSide: meta.axisSide,
    space: 16,
    child: Text(text, style: style),
  );
}

内容的提问来源于stack exchange,提问作者Guillermo Brun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:10:15