Add mentions in your Flutter app (don’t @ me)
We all love to add elements in our app that enhance the overall experience for the end user. One such addition to a typical chat module in your app would be @mentions.
In a group chat, mentions play a huge role. They help the participants refer to other participants in messages, which enables them to collaborate easily in a crowded group chat. If you use any of the apps like WhatsApp, Instagram, Facebook etc, you already know what I am talking about.
Enabling mentions in your app can be a bit tricky, as you would have to put a module in place that helps recognizing the mentions syntax i.e. anything starting with “@”. This would then trigger a series of UI elements which will help you then select one of the group participants and then add them to your text widget with unique styling to distinguish it from the normal text elements in your message.
Alright, let’s code.
Step 1:
Import the following in your project:
Now that you have done that, we would be using the capabilities of these packages to setup our mentions module.
Step 2:
We would now be creating two classes, one to help us detect the mentioned text in the message, we would be using a regex for that and another to style the mentioned element.
In the example shared below, ColoredBoxInlineSyntax class is responsible for detection and ColoredBoxMarkdownElementBuilder is responsible for formatting the detected text.
Example:
The main intention of this example is to serve the basic purpose of this article, i.e. letting you know how you can start to integrate the mentions logic in your code. The final implementation might differ depending on your chat service vendor.
Visual representation of the code above:
As you can see from the GIF above, the formatting works as expected.
We used the power of Markdown to help us format our text on the screen.
Before ending the article, here are the things you can try for yourself:
- You can use the same idea to add “#” detection in your application as well.
- Try and show an overlay over text field to select the group members from, just like WhatsApp.
- Try different BG and text color for mentions and hashtags.
Hope you find this article helpful.
How many claps does this article deserve?
If you find this article useful, please click the 👏 button and share to help others find it! Feel free to clap many times (10💥, 20💥 , or maybe 50💥 ?) It fuels my focus to write more of it.
Connect with me on LinkedIn or say hi on Twitter, mentioning this article. You can drop an e-mail at annsh29@gmail.com as well.
Check out my series on various Flutter widgets here -