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

Flutter中如何设置文本固定宽度以实现容器垂直对齐?

解决方案

要实现你要的效果,用Flutter内置组件和属性就能简洁搞定,直接看修改方案:

核心调整点

  • 用IntrinsicWidth包裹外层Column,让所有子Row的宽度统一匹配最宽的元素(也就是最长的百分比文本)
  • 给每个Text组件添加:
    • overflow: TextOverflow.ellipsis:超长文本自动显示省略号
    • maxLines: 1:限制文本仅显示一行
    • textAlign: TextAlign.right:短文本自动左补空格(若需右补空格,改用TextAlign.left)
  • 给Text套一层SizedBox(width: double.infinity),确保它占满分配的固定宽度

修改后的完整代码

Widget example() {
  return IntrinsicWidth(
    child: Column(
      children: [
        Row(
          children: [
            Expanded(
              child: Container(
                height: 100,
                decoration: const BoxDecoration(color: Colors.red),
              ),
            ),
            const SizedBox(
              width: double.infinity,
              child: Text(
                '25.00%',
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                textAlign: TextAlign.right,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Expanded(
              child: Container(
                height: 100,
                decoration: const BoxDecoration(color: Colors.red),
              ),
            ),
            const SizedBox(
              width: double.infinity,
              child: Text(
                '125.00%',
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                textAlign: TextAlign.right,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Expanded(
              child: Container(
                height: 100,
                decoration: const BoxDecoration(color: Colors.red),
              ),
            ),
            const SizedBox(
              width: double.infinity,
              child: Text(
                '1250.00%',
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                textAlign: TextAlign.right,
              ),
            ),
          ],
        ),
        // 测试超长文本的省略效果
        Row(
          children: [
            Expanded(
              child: Container(
                height: 100,
                decoration: const BoxDecoration(color: Colors.red),
              ),
            ),
            const SizedBox(
              width: double.infinity,
              child: Text(
                '999999.99%',
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                textAlign: TextAlign.right,
              ),
            ),
          ],
        ),
      ],
    ),
  );
}

效果说明

  • 所有红色Container会因右侧Text宽度统一而保持垂直对齐
  • 短百分比文本会自动在左侧补空格(右对齐设置),视觉上整齐排列
  • 超出宽度的文本会显示省略号,不会撑宽布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:21:00