Flutter 如何给搜索结果中与搜索栏输入匹配的指定字符上色?
Flutter 搜索结果匹配字符高亮实现方案
实现该需求的核心是使用RichText组件,将原始文本拆分为普通文本段和匹配到的关键字段,分别为两段设置不同的文字样式即可,以下是可直接复用的实现步骤:
1. 封装高亮文本通用工具方法
List<TextSpan> buildHighlightedTextSpans({ required String originalText, required String keyword, required TextStyle normalStyle, required TextStyle highlightStyle, }) { // 不需要大小写不敏感匹配可删除转小写逻辑 final lowerOriginal = originalText.toLowerCase(); final lowerKeyword = keyword.toLowerCase(); List<TextSpan> spans = []; int start = 0; while (start < originalText.length) { final matchIndex = lowerOriginal.indexOf(lowerKeyword, start); if (matchIndex == -1) { spans.add(TextSpan(text: originalText.substring(start), style: normalStyle)); break; } // 添加匹配位置之前的普通文本 if (matchIndex > start) { spans.add(TextSpan(text: originalText.substring(start, matchIndex), style: normalStyle)); } // 添加匹配到的关键字段,应用高亮样式 spans.add(TextSpan( text: originalText.substring(matchIndex, matchIndex + keyword.length), style: highlightStyle, )); start = matchIndex + keyword.length; } return spans; }
2. 在搜索列表项中调用
在搜索结果列表的item构建逻辑中调用上述方法即可,示例代码:
// 从搜索栏控制器获取输入的关键字,示例:_searchController.text String searchKeyword = "dart"; // 列表项的原始文本内容 String itemContent = "Dart 异步编程实战教程"; @override Widget build(BuildContext context) { return ListTile( title: RichText( text: TextSpan( children: buildHighlightedTextSpans( originalText: itemContent, keyword: searchKeyword, normalStyle: const TextStyle(color: Colors.black, fontSize: 15), highlightStyle: const TextStyle(color: Colors.blueAccent, fontSize: 15, fontWeight: FontWeight.w600), ), ), ), ); }
补充说明
- 支持同一段文本中多处匹配关键字的场景,所有匹配到的内容都会自动应用高亮样式
- 高亮样式可自定义,除了修改颜色外还可设置加粗、下划线、背景色等效果
- 如需区分大小写匹配,直接删除工具方法中转小写的逻辑,用原始字符串做匹配即可
内容的提问来源于stack exchange,提问作者SinaMN75
相关产品推荐
相关产品推荐

