You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web页面含空格文本搜索无法高亮问题

Flutter Web 含空格搜索文本高亮不完整问题修复

问题分析

当搜索文本包含空格时,仅高亮首个单词但计数显示正确,核心原因是匹配逻辑默认按空格拆分单词,或是正则表达式错误地使用了单词边界(\b)导致多词短语无法被完整匹配。

解决方案

1. 修正正则匹配规则

避免使用单词边界限制,改用转义后的完整搜索文本进行匹配,确保含空格的短语被整体识别:

// 错误写法(拆分空格,仅匹配单个单词)
RegExp wrongReg = RegExp(r'\b' + searchText + r'\b', caseSensitive: false);

// 正确写法(匹配完整含空格的搜索文本)
RegExp correctReg = RegExp(RegExp.escape(searchText), caseSensitive: false);

2. 调整文本高亮拆分逻辑

通过allMatches获取所有完整匹配的区间,逐个生成高亮文本片段:

List<TextSpan> buildHighlightSpans(String originalText, String searchText) {
  if (searchText.trim().isEmpty) return [TextSpan(text: originalText)];
  
  final regExp = RegExp(RegExp.escape(searchText), caseSensitive: false);
  final matches = regExp.allMatches(originalText);
  int lastPosition = 0;
  final spans = <TextSpan>[];

  for (final match in matches) {
    // 添加匹配前的普通文本
    if (match.start > lastPosition) {
      spans.add(TextSpan(text: originalText.substring(lastPosition, match.start)));
    }
    // 添加高亮文本
    spans.add(TextSpan(
      text: originalText.substring(match.start, match.end),
      style: const TextStyle(
        color: Colors.deepOrange,
        fontWeight: FontWeight.w600,
      ),
    ));
    lastPosition = match.end;
  }

  // 添加剩余的普通文本
  if (lastPosition < originalText.length) {
    spans.add(TextSpan(text: originalText.substring(lastPosition)));
  }

  return spans;
}

3. 校验搜索计数逻辑

确保计数逻辑基于完整短语的匹配结果,而非单个单词的匹配数,保证计数与高亮行为一致。

注意事项

若搜索文本包含正则特殊字符(如.、*、+),RegExp.escape会自动转义这些字符,避免正则语法错误。

内容的提问来源于stack exchange,提问作者Vishnu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 16:02:11