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

Flutter如何让图表适配固定容器?解决RenderBox布局报错

解决Flutter中BarChart固定容器显示及FittedBox报错问题

报错原因

使用FittedBox包裹BarChart时出现的RenderBox was not laid out错误,本质是FittedBox要求子组件具备明确的布局尺寸,但默认的charts_flutter图表会根据父组件约束无限扩展,形成布局依赖循环,触发断言检查失败。

解决方案

要实现固定尺寸容器内显示图表,需先给BarChart指定明确的原始绘制尺寸,再通过FittedBox将其缩放到外层容器的大小,彻底避免布局冲突。

修改后的代码示例:

return Container(
  width: 300, // 外层固定显示宽度
  height: 200, // 外层固定显示高度
  child: FittedBox(
    fit: BoxFit.contain, // 按比例适配容器
    child: SizedBox(
      width: 600, // 图表原始绘制宽度
      height: 400, // 图表原始绘制高度
      child: charts.BarChart(
        seriesList,
        animate: animate,
        primaryMeasureAxis: charts.NumericAxisSpec(
          tickProviderSpec: charts.StaticNumericTickProviderSpec(
            <charts.TickSpec<num>>[
              charts.TickSpec(0.8, label: ''),
              charts.TickSpec(0, label: '0'),
              charts.TickSpec(0.38, label: '0.38'),
              charts.TickSpec(0.67, label: '0.67'),
              charts.TickSpec(0.96, label: '0.96'),
              charts.TickSpec(1.25, label: '1.25'),
            ],
          ),
        ),
      ),
    ),
  ),
);

说明

  • SizedBox为BarChart提供了确定的布局边界,避免图表无限制扩展。
  • FittedBox会将SizedBox内的图表按比例缩放到外层Container的固定尺寸,既实现类似picture1的显示效果,又解决了布局断言错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 13:40:34