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

Flutter容器内文本溢出求助:实现自动换行并扩展容器

解决Flutter容器内文本自动换行及容器扩展问题

问题原因

你的代码存在两个核心问题:

  • 文本所在的Text组件未被Flexible/Expanded包裹,在Row布局中默认会强制单行显示,超出部分直接溢出。
  • 嵌套了不必要的Row组件,且外层SizedBox未设置合理约束,导致容器无法根据文本内容自动调整尺寸。

修改后的完整代码

Widget myContainer({required String title}) {
  return Padding(
    padding: const EdgeInsets.only(bottom: 5.0),
    child: GestureDetector(
      onTap: () {
        print("Das hat funktioniert");
      },
      child: Container(
        width: double.infinity, // 让容器占满父级可用宽度
        decoration: BoxDecoration(
          color: const Color.fromRGBO(86, 89, 94, 1),
          borderRadius: BorderRadius.circular(15.0),
          border: Border.all(
            color: Color.fromRGBO(255, 128, 0, 1),
            width: 2,
          ),
        ),
        padding: EdgeInsets.only(top: 10, bottom: 10, left: 12), // 合并内边距
        child: Text(
          title,
          style: TextStyle(
            color: Colors.white,
            fontSize: 22,
            fontWeight: FontWeight.w400,
          ),
          softWrap: true, // 确保文本自动换行
        ),
      ),
    ),
  );
}

关键修改点说明

  • 移除多余的嵌套Row和SizedBox,简化布局层级,避免约束冲突。
  • 给容器添加width: double.infinity,让容器横向占满父级空间,纵向会根据文本高度自动扩展。
  • 开启Text的softWrap: true属性,确保文本超出宽度时自动换行。

如果需要保留原Row布局(比如后续要添加右侧组件),则需用Flexible包裹文本所在子组件,示例如下:

// 保留Row布局的版本
Widget myContainer({required String title}) {
  return Padding(
    padding: const EdgeInsets.only(bottom: 5.0),
    child: GestureDetector(
      onTap: () {
        print("Das hat funktioniert");
      },
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: const Color.fromRGBO(86, 89, 94, 1),
          borderRadius: BorderRadius.circular(15.0),
          border: Border.all(
            color: Color.fromRGBO(255, 128, 0, 1),
            width: 2,
          ),
        ),
        padding: EdgeInsets.only(top: 10, bottom: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Flexible( // 核心:用Flexible包裹文本子组件
              child: Padding(
                padding: const EdgeInsets.only(left: 12.0, top: 14, bottom: 14),
                child: Text(
                  title,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 22,
                    fontWeight: FontWeight.w400,
                  ),
                  softWrap: true,
                ),
              ),
            ),
            // 可在此添加右侧其他组件
          ],
        ),
      ),
    ),
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:21:08