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
相关产品推荐
相关产品推荐

