Flutter中如何高效实现Row组件内Container占满剩余宽度
要实现右侧容器自适应占满Row剩余宽度,只需用Expanded组件包裹右侧Container,同时为了避免CrossAxisAlignment.stretch的高度报错,给Row添加明确的高度约束即可,具体实现如下:
完整修正代码
child: ListView( padding: const EdgeInsets.symmetric(horizontal: 20), children: [ const SizedBox(height: 5), // 给Row添加固定高度约束,匹配左侧图片高度 SizedBox( height: 80, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, // 此时有明确高度约束,不会报错 children: [ Container( width: 80, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), image: const DecorationImage( image: NetworkImage('http://images.unsplash.com/photo-1555010133-d883506aedee?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max'), fit: BoxFit.cover ) ), ), const SizedBox(width: 10), // Expanded自动占用Row剩余宽度,无需写死width Expanded( child: Container( color: Colors.green, // 父级设置了stretch,高度自动撑满,无需单独设置 ), ) ], ), ), ], ),
相关问题说明
- 固定宽度适配差的问题:
Expanded仅可作为Row、Column、Flex的子组件使用,会自动分配父级Flex容器中除固定尺寸子组件外的所有剩余空间,可自动适配所有屏幕宽度。 CrossAxisAlignment.stretch报无限高度错误的原因:该属性要求子元素高度撑满父容器,但未加高度约束的Row本身高度无上限,系统无法判断拉伸的边界,因此触发报错。给Row外层套固定高度的SizedBox后,父级高度明确,即可正常用stretch实现左右子组件高度统一。
如果右侧是动态文本,需要高度自适应内容,可去掉外层SizedBox和stretch属性,单独给左侧图片设置高度即可:
Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: 80, width: 80, // 图片配置省略 ), const SizedBox(width: 10), Expanded( child: Container( color: Colors.green, child: const Text('动态文本内容,高度随文本长度自动调整,宽度自动占满剩余空间'), ), ) ], )
内容的提问来源于stack exchange,提问作者Mann
相关产品推荐
相关产品推荐

