flutter 高亮字符,富文本

高亮【keywords】关键字

javascript 复制代码
import 'package:flutter/material.dart';

/// 富文本,高亮字符
class HighlightedText extends StatelessWidget {
  final String text;
  final List<String> keywords;  //关键字
  final Color highlightColor;    //高亮颜色
  final TextStyle normalStyle;   //正常字体样式
  final TextStyle highlightStyle;  //高亮字体样式
  final int? maxLines;
  final TextOverflow overflow;
  final TextAlign textAlign;

  const HighlightedText({
    super.key,
    required this.text,
    required this.keywords,
    this.highlightColor = Colors.red,
    this.normalStyle = const TextStyle(),
    this.highlightStyle = const TextStyle(),
    this.textAlign = TextAlign.start,
    this.maxLines,
    this.overflow = TextOverflow.ellipsis,
  });

  @override
  Widget build(BuildContext context) {
    /// 如果没有关键词,直接返回普通文本
    if (keywords.isEmpty || text.isEmpty) {
      return Text(text, style: normalStyle);
    }

    /// 过滤掉空关键词
    final validKeywords = keywords.where((keyword) => keyword.isNotEmpty).toList();
    if (validKeywords.isEmpty) {
      return Text(text, style: normalStyle);
    }

    /// 创建正则表达式来匹配所有关键词(按长度降序排列,避免短关键词优先匹配)
    validKeywords.sort((a, b) => b.length.compareTo(a.length));

    final pattern = RegExp(
      validKeywords.map((keyword) => RegExp.escape(keyword)).join('|'),
      caseSensitive: false,
    );

    final matches = pattern.allMatches(text);
    final spans = <TextSpan>[];
    int lastEnd = 0;

    /// 遍历所有匹配项
    for (final match in matches) {
      /// 添加匹配前的普通文本
      if (match.start > lastEnd) {
        spans.add(TextSpan(
          text: text.substring(lastEnd, match.start),
          style: normalStyle,
        ));
      }

      /// 获取匹配的文本
      final matchedText = text.substring(match.start, match.end);

      /// 添加高亮的关键词 - 修复样式合并问题
      spans.add(TextSpan(
        text: matchedText,
        style: highlightStyle.merge(TextStyle(
          color: highlightColor,
          fontWeight: FontWeight.bold,
        )),
      ));

      lastEnd = match.end;
    }

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

    /// 如果没有匹配到任何关键词,返回普通文本
    if (spans.isEmpty) {
      return Text(text, style: normalStyle);
    }

    return RichText(
      maxLines: maxLines,
      overflow: overflow,
      textAlign: textAlign,
      text: TextSpan(children: spans),
    );
  }
}
相关推荐
Fungleo1069979 小时前
Flutter/Android Release 包连不上网?AndroidManifest INTERNET 权限排查实录
flutter
GitLqr11 小时前
Flutter 实战:为你的 App 增加桌面快捷方式 (Quick Actions)
flutter·app·全栈
FungLeo13 小时前
Flutter 把第三方 UI 库渐进迁回 Material 3:组件映射总表 + 四批次替换实战
flutter·ui
GitLqr2 天前
iOS 27 强制要求 UISceneDelegate:UIKit 和 Flutter 开发者该如何应对?
flutter·ios·全栈
蜡台2 天前
Flutter HTTP 请求完整详解
网络协议·flutter·http·dart
9765033352 天前
iOS 上架/审核 4.3a Cocos 2026最新方案解读
flutter·ios·swift·cocos2d·ios开发
FungLeo2 天前
Flutter 接入 Alice 调试浮窗:一个顶层 final 抢跑,把 release 网络整没了
网络·flutter
恋猫de小郭3 天前
Flutter hit,一个可以灵活控制溢出点击的第三方包
android·前端·flutter
蜡台4 天前
Flutter Container 与装饰完整讲解
android·javascript·flutter·dart
杉氧4 天前
跨平台持久化:Flutter 本地数据库的多线程安全与架构设计实践
android·前端·flutter