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

Flutter实现Instagram克隆评论中@用户标签的蓝色高亮

实现评论中@用户的蓝色高亮效果

不用硬编码TextSpan,你可以封装一个工具函数,自动将文本中的@标签转换成带样式的TextSpan,不管标签在文本的任意位置都能自动处理:

步骤1:编写正则表达式匹配@标签

先定义匹配规则,匹配以@开头,直到遇到空格、标点或文本结束的内容:

final RegExp mentionRegex = RegExp(r'@\w+');

步骤2:封装生成TextSpan数组的工具函数

这个函数会把原始文本拆分成普通文本和@标签的片段,给标签设置蓝色样式,还可以添加点击事件(模拟Instagram的跳转功能):

List<TextSpan> buildMentionSpans(String text, {VoidCallback? onMentionTap}) {
  List<TextSpan> spans = [];
  int currentIndex = 0;

  // 遍历所有匹配到的@标签
  mentionRegex.allMatches(text).forEach((match) {
    // 添加标签之前的普通文本
    if (match.start > currentIndex) {
      spans.add(TextSpan(
        text: text.substring(currentIndex, match.start),
        style: const TextStyle(color: Colors.black),
      ));
    }
    // 添加带样式的@标签
    spans.add(TextSpan(
      text: match.group(0),
      style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.w500),
      recognizer: TapGestureRecognizer()
        ..onTap = () {
          if (onMentionTap != null) onMentionTap();
          // 这里可以添加跳转到用户主页的逻辑
        },
    ));
    currentIndex = match.end;
  });

  // 添加最后一段普通文本
  if (currentIndex < text.length) {
    spans.add(TextSpan(
      text: text.substring(currentIndex),
      style: const TextStyle(color: Colors.black),
    ));
  }

  return spans;
}

步骤3:在RichText中使用这个函数

直接传入评论文本,就能自动生成带蓝色@标签的富文本:

RichText(
  text: TextSpan(
    children: buildMentionSpans(
      "Hey @john_doe, check out this post! @jane_smith might like it too.",
      onMentionTap: () {
        // 处理@标签的点击事件
      },
    ),
  ),
)

可选:使用第三方库简化开发

如果你不想自己写正则和拆分逻辑,可以用flutter_linkify库,自定义匹配规则来识别@标签:

  1. 添加依赖到pubspec.yaml:
dependencies:
  flutter_linkify: ^6.0.0
  1. 自定义匹配器:
Linkify(
  text: "Hey @john_doe, check out this post!",
  linkifiers: [
    CustomLinkifier(
      regex: mentionRegex,
      onTap: (url) {
        // 处理@标签点击,url就是@开头的内容
      },
    ),
  ],
  style: const TextStyle(color: Colors.black),
  linkStyle: const TextStyle(color: Colors.blue),
)

这种方式完全不需要硬编码,不管@标签在文本开头、中间还是结尾,都能自动识别并设置样式,和Instagram的效果一致。

内容的提问来源于stack exchange,提问作者Moulik Gupta 50

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:17:19