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

Flutter:如何避免Row组件溢出同时保持预期布局定位

Flutter 解决Expanded嵌套Row的布局溢出与预期布局冲突问题

要实现灰色Container仅占用自身内容空间、绿色Container紧跟且长文本不溢出的效果,你需要调整Container的约束和内部Row的属性,具体修正方案如下:

核心调整点:

  • 灰色Container内部的Row设置mainAxisSize: MainAxisSize.min,强制它仅占用内容所需宽度,避免被拉伸
  • 绿色Container外层使用Expanded,让它填充灰色容器剩余的可用空间
  • 绿色容器内的长文本用Flexible包裹,配合TextOverflow.ellipsis实现溢出省略

修正后的完整代码片段:

Widget getCard(BuildContext context) {
  return Card(
    child: Column(children: [
      Row(
        children: [
          Expanded(flex: 1, child: _plateNumberWidget()),
          Expanded(
            flex: 3,
            child: Container(
              color: Colors.amber,
              child: Text("2"),
            ),
          ),
          Expanded(
              flex: 8,
              child: Row(
                children: [
                  // 灰色容器:内部Row仅占内容宽度
                  Container(
                    color: Colors.grey,
                    child: Row(
                      mainAxisSize: MainAxisSize.min, // 关键:仅占用内容所需空间
                      children: [Text("Test1"), Text("Test2")],
                    ),
                  ),
                  // 绿色容器:填充剩余空间
                  Expanded(
                    child: Container(
                      color: Colors.green,
                      child: Row(
                        children: [
                          Text("Test3"),
                          Flexible(
                            child: Text(
                              "Test444444444444444444444444",
                              overflow: TextOverflow.ellipsis,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ))
        ],
      ),
      Row(children: []),
      Row(children: []),
      Row(children: []),
    ]),
  );
}

效果说明:

  • 灰色容器会紧贴"Test2"文本,仅占用自身内容的宽度
  • 绿色容器会紧跟灰色容器,填满Expanded分配的剩余空间
  • 绿色容器内的长文本会自动截断并显示省略号,不会造成布局溢出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:05:20