Flutter 文字溢出省略中间或前面

文字溢出

当文字过长,通常会换行(softWrap)、以省略号替代溢出的部分(ellipsis)、渐隐(fade)。以上的方案,可以通过设置Text的overflow、softWrap属性实现。

TexrOverflow.ellipsis

想法

但如果想要隐藏文字的中间部分,或者开头部分,该如何实现?

实现

可以返回一个LayoutBuilder对象,
通过内部的builder属性的size参数,测算可以显示多少个字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
LayoutBuilder(builder: (context, size) {
/// 是否溢出
bool exceeded = false;
/// 可以显示的文字长度
int len = 0;

for (; !exceeded && len < str!.length; len++) {
// Build the textspan
var span = TextSpan(
text: '...' + str.substring(str.length - len),
style: TextStyle(
fontSize:
Theme.of(context).textTheme.bodyText1?.fontSize ??
14),
);
// 使用[TextPainter]来校验文字是否超过了[maxLines]
var tp = TextPainter(
maxLines: 1,
textAlign: TextAlign.left,
textDirection: TextDirection.ltr,
text: span,
);
// 使其布局来校验
tp.layout(maxWidth: size.maxWidth);
// 根据[tp]的布局结果的[didExceedMaxLines]属性来判断是否溢出
exceeded = tp.didExceedMaxLines;
}
return Text(
/// 构造Text,此处为省略前面的部分,替换为省略号
(exceeded ? '...' : '') + str!.substring(str.length - len),
overflow: TextOverflow.clip,
maxLines: 1,
style: const TextStyle(color: Colors.grey),
);
})

效果

源码

Github