美文网首页
Text 组件文本超长显示省略号后部分空白的解决方法

Text 组件文本超长显示省略号后部分空白的解决方法

作者: zackzheng | 来源:发表于2023-07-21 14:05 被阅读0次

Flutter 使用 Text 组件,设置文本超长时显示省略号,当被截取的单词超长时,尾部容易出现一片空白。期望是被截取的单词仍然能显示一部分,显示不了的部分使用省略号。

示例如下:
原文为 hello pneumonoultramicyoscpicailicovolcanoconiosis

实际效果:


flutter_text_ellipsis_fixed.jpg

使用以下方式可以解决:

extension EllipsisFixed on String {
  String get ellipsisFixed => Characters(this).join('\u{200B}');
}

如果项目支持阿拉伯语,则会出现文本变宽的问题。可以对文本进行判断,如果包含阿拉伯语则不处理:

extension ArabicExtension on String {
  /// 判断是否包含阿拉伯语
  bool get hasArabicGlyphs {
    final codeUnits = this.codeUnits;
    for (int i = 0; i < codeUnits.length; i++) {
      final codeUnit = codeUnits[I];
      if (codeUnit >= 0x600 && codeUnit <= 0x6ff) return true;
      if (codeUnit >= 0x750 && codeUnit <= 0x77f) return true;
      if (codeUnit >= 0xfb50 && codeUnit <= 0xfc3f) return true;
      if (codeUnit >= 0xfe70 && codeUnit <= 0xfefc) return true;
    }
    return false;
  }
}
extension EllipsisFixed on String {
  String get ellipsisFixed => this.hasArabicGlyphs ? this : Characters(this).join('\u{200B}');
}

使用 replaceAll('', '\u{200B}'); 的方式处理,会报异常:string is not well-formed UTF-16

相关文章

网友评论

      本文标题:Text 组件文本超长显示省略号后部分空白的解决方法

      本文链接:https://www.haomeiwen.com/subject/otstpdtx.html