I have a String that includes mentions with an @ tag and I want to create a richtext, where every tag is included in a map of mentions with usernames and userIds is highlighted and make it clickable.
// dummy class
class Reply {
List<dynamic> mentions;
String? text;
Reply({required this.mentions, required this.text});
}
// sample reply
Reply sample = Reply(
mentions: [
{'username': 'sampleUser1', 'userId': '0x123'},
{'username': 'sampleUser2', 'userId': '0x321'}
],
text: 'This text mentions @0x123 as well as @0x321',
);
// replacing all matching ids with the respective usernames
for (var ment in sample.mentions) {
sample.text = sample.text!.replaceAll(ment['userId'], ment['username']);
}
print(sample.text); // This text mentions @sampleUser1 as well as @sampleUser2
This is where I got stuck. I want to create a richtext that highlights the usernames in the text in bold and make it clickable.
RichText(
text: TextSpan(
children: 'sample sample' /*sample.text goes here*/
.split(' ') /*find words that start with '@' and include a username that can also be found in the list of mentions*/
.map((word) => TextSpan(
text: word + ' ',
style: TextStyle(
fontWeight:
true /*condition if word is found in mentions*/
? FontWeight.bold
: FontWeight.normal),
recognizer: TapGestureRecognizer()
..onTap =
true /*condition if word is found in mentions*/
? () {
/*do something*/
}
: () {
/*do nothing*/
}))
.toList())),
Any help is appreciated, I will keep trying, and update here when I figure it out.