检测文本中的 @ 并将其显示为 link (Flutter)

Detect @ in text and show it as link (Flutter)

我想知道如何创建一个识别器来检测文本中的 @ 并将其颜色更改为蓝色,并为其添加 onTap 功能 :) 就像这张照片。

我认为这应该适用于@someone:

您需要导入这个:import 'package:flutter/gestures.dart';

这是您的输入字符串:String input = "This is a long text but in between there should be this: @someone The text continues here, but there is @another.";

这是我为您制作的小部件:textSplitter(input);

Widget textSplitter(String input) {
  List<TextSpan> textSpans = [];
  
  for (var i = 0; i <= '@'.allMatches(input).length; i++) {
    String part = input.substring(0, input.indexOf('@')==-1? input.length : input.indexOf('@'));
    textSpans.add(TextSpan(text: part, style: TextStyle(color: Colors.white)));

    input = input.substring(input.indexOf('@'));
    String clickable = input.substring(0, input.indexOf(' ')==-1? input.length : input.indexOf(' '));
    textSpans.add(
      TextSpan(
        text: clickable,
        style: TextStyle(
          color: Colors.blue,
          decoration: TextDecoration.underline,
        ),
        recognizer: new TapGestureRecognizer()
          ..onTap = () {
            //do stuff here with string clickable
            print(clickable);
          },
      ),
    );
    input = input.substring(input.indexOf(' ')==-1? input.length : input.indexOf(' '));
  }

  return RichText(
    text: TextSpan(
      children: textSpans,
    ),
  );
}

结果应如下所示:

请注意,在 space 之前包含 @ 之后的任何内容。