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.
-
do you want to recognize an email address or an Instagram profile?MindStudio– MindStudio2021-03-14 20:24:20 +00:00Commented Mar 14, 2021 at 20:24
Add a comment
|
1 Answer
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: 
Note that anything after the @ is included until a space.
1 Comment
Soheil_PFP
Correct ✅ Thanks for your useful and clean answer :)