Flutter开发 - 对于富文本展示的方法封装

1,143 阅读2分钟

1.简单富文本
在富文本展示过程中,如果只有1-2段文字需要富文本,且是位于收尾的这种,如:

0天后;
30

这样的富文本处理起来是很容易的,可以这么做:

Widget richTextWidget({String normalStr, String highightStr}) {
  TextStyle normalStyle = TextStyle(fontSize: 13, color: Color(0xFFA5ABB6), fontWeight: FontWeight.w400);
  TextStyle highlighStyle = TextStyle(fontSize: 13, color: Color(0xFF4A87FD), fontWeight: FontWeight.w400);
  List<TextSpan> spans = [];
  spans.add(TextSpan(text: highightStr, style: highlighStyle));
  spans.add(TextSpan(text: normalStr, style: normalStyle));
  return RichText(
    maxLines: 1,
    overflow: TextOverflow.ellipsis,
    text: TextSpan(children: spans),
  );
}

用这个方法,调整富文本的顺序即可返回一个富文本Widget。

2.复杂富文本
如果富文本的内容是由后端返回的包含前端html标签的文字,且一段文字中可能有多个词语是需要高亮显示的,这时候就需要具体问题具体分析了,假如:

阿萨精神病的<em>高亮</em>卡不是表达势不可挡吧<em>高亮</em>可是不可得兼啊不看<em>高亮</em>世界杯的空间阿巴斯基本的框架阿巴斯就不打就不睡觉的卡上

上面这段是博主随手打的文字,用高亮标签,也可以是其他的标签,括起来的是需要高亮的文字,看如下封装:

Widget _title(String name) {
  TextStyle normalStyle = TextStyle(fontSize: 15, color: Colors.black, fontWeight: FontWeight.bold);
  TextStyle highlighStyle = TextStyle(fontSize: 15, color: Color.fromRGBO(255, 73, 28, 1), fontWeight: FontWeight.w500);
  //把标签替换成普通的特殊字符,确保你的这段内容中没有这些字符,如果有多种不同标签,也可以这么来做
  String result = name.replaceAll('<em>', '?');
  String results = result.replaceAll('</em>', '@');
  List<TextSpan> spans = [];
  //这里两个变量是为了处理高亮位于头和尾的情况
  int startIndex = -1;
  int endIndex = -1;
//找到哪些是高亮的哪些是黑色的。
  for (int i = 0; i < results.length; i++) {
    String str = results[i];
    if (str == '?') {
      print('高亮了');
      startIndex = i + 1;
      endIndex = -1;
    }
    if (str == '@') {
      print('结束了');
      endIndex = i;
      startIndex = -1;
    }
    ///这里不理解的把i从0开始往里带入下就知道了,要考虑?@可能存在于首和尾
    if (i != startIndex - 1 && i != endIndex) {
      if (startIndex > 0) {
        if (i >= startIndex && endIndex < 0) {
          print('highlighStyle:' + str);
          spans.add(TextSpan(text: str, style: highlighStyle));
        }
      }

      if (endIndex > 0 || startIndex < 0) {
        spans.add(TextSpan(text: str, style: normalStyle));
      }
    }
  }
  return RichText(
    maxLines: 1,
    overflow: TextOverflow.ellipsis,
    text: TextSpan(children: spans),
  );
}

这样,一段文字中就可以出现多个高亮的文字了,这些高亮的文字都可以单独设置颜色,字体等。