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

Flutter实现:让Row中子容器高度匹配最高兄弟元素

解决方案

问题出在两个核心点:Row子元素默认不会拉伸高度,且Expanded的嵌套方式错误导致布局约束失效。按以下步骤修改即可解决:

  1. 修正Expanded嵌套错误:原代码里第一个Container包裹Expanded是违规写法,Expanded必须作为Row的直接子节点才能正确分配空间,直接移除该外层Container。
  2. 让Row子元素拉伸高度:给最外层的Row添加crossAxisAlignment: CrossAxisAlignment.stretch,这会让所有子元素自动填充Row的整体高度(也就是文本撑开的卡片高度)。
  3. 移除灰色容器固定高度:删掉灰色容器的height:50属性,它会自动跟随Row的高度,和外层卡片保持一致。

修改后的完整代码:

return Container(
  decoration: BoxDecoration(
      borderRadius: BorderRadius.all(Radius.circular(10)),
      border: Border.all(width: 1, color: Colors.grey.shade400),
      color: Colors.grey.shade100),
  child: Container(
    padding: EdgeInsets.all(8),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch, // 添加该行
      children: [
        // 移除外层Container,直接放置Expanded
        Expanded(
            child: Text(
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")),
        Expanded(
          child: Container(
            child: const Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Icon(Icons.edit_outlined),
                  Icon(Icons.delete_outlined)
                ]),
          ),
        ),
        Container(
            decoration: const BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(10)),
              color: Colors.grey,
            ),
            width: 10
            // 移除固定height属性
            ),
      ],
    ),
  ),
);

修改完成后,外层卡片会自适应文本内容的高度,灰色容器也会自动填满卡片的高度,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:35:20