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

Flutter中Expanded包裹的Container无法填充颜色问题求助

问题分析与解决

你的问题出在包含Row的外层Container没有设置高度约束:
Flutter布局遵循"约束-尺寸-位置"的规则,当前Row的高度仅由子元素中高度最高的(右侧50×50的灰色Container)决定,但Expanded包裹的红色Container没有垂直方向的约束,会自动收缩到最小高度(0),所以看不到红色背景。

几种可行的解决办法

方案一:给外层Container设置固定高度

让Row填满指定高度,Expanded的红色Container会自动填充水平和垂直空间:

Container(
  padding: const EdgeInsets.only(top:50,left:20),
  height: 50, // 添加固定高度
  child: Row(
    children: [
      Icon(Icons.menu,size:30,color:Colors.black54),
      Expanded(child: Container(
        color: Colors.red,
      )),
      Container(
        margin: const EdgeInsets.only(right:20),
        width: 50,
        height: 50,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.grey.withOpacity(0.5),
        ),
      )
    ],
  ),
)

方案二:让Row自适应子元素最大高度并拉伸

用IntrinsicHeight包裹Row,配合CrossAxisAlignment.stretch让子元素填满垂直空间:

Container(
  padding: const EdgeInsets.only(top:50,left:20),
  child: IntrinsicHeight(
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.stretch, // 强制子元素拉伸填满高度
      children: [
        Icon(Icons.menu,size:30,color:Colors.black54),
        Expanded(child: Container(
          color: Colors.red,
        )),
        Container(
          margin: const EdgeInsets.only(right:20),
          width: 50,
          height: 50,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colors.grey.withOpacity(0.5),
          ),
        )
      ],
    ),
  ),
)

方案三:直接给红色Container设置高度

和右侧灰色容器保持一致的高度,快速看到效果:

Expanded(child: Container(
  color: Colors.red,
  height: 50, // 手动设置高度
)),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:30:53