2

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

1
  • do you want to recognize an email address or an Instagram profile? Commented Mar 14, 2021 at 20:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Correct ✅ Thanks for your useful and clean answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.