美文网首页Flutter
flutter-搜索匹配高亮显示核心算法

flutter-搜索匹配高亮显示核心算法

作者: ChaosHeart | 来源:发表于2020-10-08 09:40 被阅读0次

1.英文(只英文推荐)

 //搜索的字符
  String _searchStr = '';

  //正常文本
  TextStyle _normalStyle = TextStyle(
    fontSize: 16,
    color: Colors.black,
  );

  //高亮文本
  TextStyle _highlightStyle = TextStyle(
    fontSize: 16,
    color: Colors.blue,
  );

  ///返回设置好的富文本
  Widget _splitEnglish(String name) {
    List<TextSpan> spans = [];
    //split 截出来
    List<String> strs = name.split(_searchStr);
    print("搜索字符截出来是: $strs");
    for (int i = 0; i < strs.length; i++) {
      //拿出字符串
      String str = strs[i];
      //为空字符串的都是高亮
      if (str == '' && i < strs.length - 1) {
        spans.add(TextSpan(text: _searchStr, style: _highlightStyle));
      } else {
        //其他
        spans.add(TextSpan(text: str, style: _normalStyle));
        //最后一个字符
        if (i < str.length - 1) {
          spans.add(TextSpan(text: _searchStr, style: _highlightStyle));
        }
      }
    }
    //返回
    return RichText(
      text: TextSpan(children: spans),
    );
  }

2.通用(可用中文和英文)

  ///4.4.返回设置好的富文本
  Widget _splitChina(String name) {
    List<TextSpan> spans = [];
    //split 截出来
    List<String> strS = name.split(_searchStr);
    print("搜索字符截出来是: $strS");
    //字符从匹配高亮
    for (int i = 0; i < strS.length; i++) {
      if ((i % 2) == 1) {
        spans.add(TextSpan(text: _searchStr, style: _highlightStyle));
      }
      String val = strS[i];
      if (val != '' && val.length > 0) {
        spans.add(TextSpan(text: val, style: _normalStyle));
      }
    }
    //返回
    return RichText(
      text: TextSpan(children: spans),
    );
  }

相关文章

网友评论

    本文标题:flutter-搜索匹配高亮显示核心算法

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