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

如何让Flutter中ListView内的Container高度匹配Row固有高度?

解决Flutter中ListView卡片内Container高度匹配Row固有高度的问题

要让卡片内的蓝色Container高度自动匹配Row的固有高度(即与内容Column的高度一致),可以通过以下两步修改代码:

  1. 给Row添加crossAxisAlignment: CrossAxisAlignment.stretch属性,让Row的所有子元素在垂直方向上拉伸,匹配Row的高度(由内部最高的子元素决定)。
  2. 给蓝色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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:13:24