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

Issue

I wonder how to create a recognizer to detect @ in the text & change its color to something like a blue one and also add onTap functionality to it 🙂 like this picture.enter image description here

Solution

I think this should work for anything like @someone:

You need to import this: import 'package:flutter/gestures.dart';

This is your input String: String input = "This is a long text but in between there should be this: @someone The text continues here, but there is @another.";

This is the widget I made for you : 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,
    ),
  );
}

The result should look like this: Result of Code

Note that anything after the @ is included until a space.

Answered By – MindStudio

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *