如何让Flutter中ListView内的Container高度匹配Row固有高度?
解决Flutter中ListView卡片内Container高度匹配Row固有高度的问题
要让卡片内的蓝色Container高度自动匹配Row的固有高度(即与内容Column的高度一致),可以通过以下两步修改代码:
- 给Row添加
crossAxisAlignment: CrossAxisAlignment.stretch属性,让Row的所有子元素在垂直方向上拉伸,匹配Row的高度(由内部最高的子元素决定)。 - 给蓝色Container设置
height: double.infinity,使其填充Row的整个高度。
修改后的完整代码:
class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( body: ListView.builder( itemCount: 10, itemBuilder: (context, index) { return Card( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container( width: 10, height: double.infinity, color: Colors.blue, ), Column( children: [ Text('A\nB\nC\nD'), ], ), Column( children: [ Text('$index'), ], ), ], ), ); }), ); } }
原理说明
CrossAxisAlignment.stretch约束Row的高度由内部最高的子元素(这里是包含多行文本的Column)撑开,同时强制所有子元素拉伸到该高度。height: double.infinity让Container填充Row的已确定高度,既无需固定值适配不同内容长度,也不会触发渲染异常——因为此时Row的高度已经由子元素明确约束,不再是无限的。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

