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),
    );
  }
}
相关推荐
王码码20351 小时前
Flutter 组件 inappwebview_cookie_manager 适配 鸿蒙Harmony 实战 - 驾驭核心大 Web 容器缓存隧道、构建金融级政企应用绝对防串号跨域大隔离基座
flutter·harmonyos·鸿蒙·openharmony·inappwebview_cookie_manager
左手厨刀右手茼蒿1 小时前
Flutter 组件 ews 的适配 鸿蒙Harmony 实战 - 驾驭企业级 Exchange Web Services 协议、实现鸿蒙端政企办公同步与高安通讯隔离方案
flutter·harmonyos·鸿蒙·openharmony
钛态1 小时前
Flutter 三方库 react 泛前端核心范式框架鸿蒙原生层生态级双向超能适配:跨时空重塑响应式单向数据流拓扑与高度精密生命周期树引擎解耦视图渲染控制中枢(适配鸿蒙 HarmonyOS ohos)
前端·flutter·react.js
键盘鼓手苏苏1 小时前
Flutter 组件 spry 适配鸿蒙 HarmonyOS 实战:轻量化 Web 框架,构建高性能端侧微服务与 Middleware 治理架构
flutter·harmonyos·鸿蒙·openharmony
wey6082 小时前
使用taro 开发 flutter应用
flutter
装不满的克莱因瓶3 小时前
【2026 持续更新】Flutter 零基础到精通全攻略(一)
flutter·app·dart·移动端
装不满的克莱因瓶4 小时前
React Native vs Flutter:一次深入到底的性能对比分析(含原理 + 实战)
javascript·flutter·react native·react.js·app·移动端
亚历克斯神5 小时前
Flutter 组件 t_stats 的适配 鸿蒙Harmony 实战 - 驾驭高性能统计学运算、实现鸿蒙端海量数据实时态势感知与工业级描述性统计方案
flutter·harmonyos·鸿蒙·openharmony·t_stats
键盘鼓手苏苏5 小时前
Flutter 组件 angel3_orm_mysql 的适配 鸿蒙Harmony 实战 - 驾驭专业 ORM 映射引擎、实现鸿蒙端与 MySQL 数据库的透明映射与高性能 SQL 审计方案
flutter·harmonyos·鸿蒙·openharmony·angel3_orm_mysql
左手厨刀右手茼蒿5 小时前
Flutter 组件 serverpod_swagger 的适配 鸿蒙Harmony 实战 - 驾驭 API 文档自动化、实现鸿蒙端全栈联调与 Swagger UI 动态审计方案
flutter·harmonyos·鸿蒙·openharmony·serverpod_swagger