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
相关产品推荐
相关产品推荐

