Flutter开发:如何实现文本向左溢出而非向右溢出?
解决Flutter文本右对齐时省略号显示在右侧的问题
你的代码有两个关键问题导致没达到预期效果:
- 未设置
maxLines: 1:Flutter的TextOverflow.ellipsis仅在限制文本行数时生效,默认多行模式下文本会自动换行,不会触发省略号效果。 - 使用
textAlign: TextAlign.end:该属性会让右对齐的文本从开头截断,省略号出现在左侧,和你想要的「xxx...」效果不符。
修改后的代码有两种方案,任选其一即可:
方案一:调整Text组件属性
Widget name({required String firstName, required String lastName}) { return Align( alignment: Alignment.centerRight, child: Text( "$firstName $lastName", textAlign: TextAlign.start, // 改为start,确保从文本末尾截断 textDirection: TextDirection.ltr, maxLines: 1, // 必须设置,触发overflow省略号逻辑 style: const TextStyle( fontWeight: FontWeight.w900, overflow: TextOverflow.ellipsis, fontSize: 16, ), ), ); }
方案二:用Row+Expanded实现
Widget name({required String firstName, required String lastName}) { return Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Expanded( child: Text( "$firstName $lastName", maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( fontWeight: FontWeight.w900, fontSize: 16, ), ), ), ], ); }
两种方案都能实现:文本整体右对齐,溢出时省略号显示在内容右侧(保留开头内容,截断末尾并添加省略号)。
内容的提问来源于stack exchange,提问作者Chhily Lim
相关产品推荐
相关产品推荐

