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

为何两个Expanded组件宽度不一致?求解释与修复方案

Flutter布局对齐问题:Personal与Sick组件宽度不一致导致数字错位

问题现象

Personal组件宽度为73,Sick组件宽度为100,两者宽度不匹配,导致组件内的数字文本无法对齐。

布局错位截图1
布局错位截图2

问题原因

第一行Row中,两个Expanded之间存在SizedBox(width:8)的间距,因此每个Expanded的实际可用宽度为 (父容器总宽度 - 8px) / 2;而第二行Row里,两个Expanded之间无额外间距,第一个Expanded的宽度直接是 父容器总宽度 / 2。两者宽度计算逻辑不一致,导致第一行的Personal组件和第二行的Sick组件宽度不等,最终内部数字文本错位。

修复方法

统一两行Row的布局结构,给第二行的两个Expanded之间也添加相同的8px间距,让两个Expanded的宽度计算逻辑和第一行保持一致。

修改后的代码

return Container(
      margin: const EdgeInsets.only(top: 12.0, right: 4.0, left: 4.0),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: StatusItem(
                  img: Assets.images.svgIcons.icPersonal.svg(
                    width: 20.0,
                    height: 20.0,
                    fit: BoxFit.contain,
                  ),
                  label: translations.personalText,
                  total: personalLeave,
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: StatusItem(
                  img: Assets.images.svgIcons.icSwitch.svg(
                    width: 20.0,
                    height: 20.0,
                    fit: BoxFit.contain,
                    color: FigmaColors.slateColor,
                  ),
                  label: translations.switchText,
                  total: switchHoliday,
                ),
              ),
            ],
          ),
          const SizedBox(
            height: 14.0,
          ),
          Row(
            children: [
              Expanded(
                child: StatusItem(
                  img: Assets.images.svgIcons.icSick.svg(
                    width: 20.0,
                    height: 20.0,
                    fit: BoxFit.contain,
                  ),
                  label: translations.sickText,
                  total: sickLeave,
                ),
              ),
              // 添加与第一行一致的间距
              const SizedBox(width: 8),
              Expanded(child: Container())
            ],
          ),
        ],
      ),
    );

其他可选方案

  • 使用GridView替代Column+Row:通过GridView.count设置crossAxisCount:2,统一每个StatusItem的宽度,同时用crossAxisSpacing设置8px间距,布局更简洁。
  • 给StatusItem设置固定宽度:如果父容器宽度固定,可直接给StatusItem设置计算好的固定宽度(比如(父容器宽度 - 8*2)/2),但灵活性不如前一种方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:20:52