Moulik Gupta 50
Moulik Gupta 50

Reputation: 186

How to change the color of specific expressions in text in flutter

I'm trying to build an instagram clone and I want if the user tags someone in the comments, the tag text should appear blue (as in real Instagram). Example. I've used regex to recognise the tags from the text but can't figure out how to color them as the user can place a tag anywhere in the comment. I tried using RichText widget along with TextSpan but quickly realised it was way too hardcoded. Is there any direct and easy way for this situation?

PS: Sorry for the bad title...

Upvotes: -1

Views: 384

Answers (1)

Emirhan Selim Uzun
Emirhan Selim Uzun

Reputation: 1100

To achieve this first create a list of strings:

List<String> _tags = [];

Then create a function that will recognize when someone is tagged:

  List<String> _extractTags(String text) {
    List<String> tags = [];
    RegExp exp = RegExp(r'\B@\w+');
    Iterable<RegExpMatch> matches = exp.allMatches(text);
    for (RegExpMatch match in matches) {
      tags.add(match.group(0));
    }
    return tags;
  }

Then use this function inside TextField's onChange method:

onChanged: (value) {
                setState(() {
                  _tags = _extractTags(value);
                });
              },

This will put tags inside _tags list. When you use this list, use it like below:

ListView.builder(
  itemCount: _tags.length,
  itemBuilder: (BuildContext context, int index) {
    String tag = _tags[index];
    TextStyle defaultStyle = TextStyle(fontSize: 16);
    TextStyle tagStyle = TextStyle(color: Colors.blue, fontSize: 16);
    List<TextSpan> spans = [];
    if (tag == null) {
      spans.add(TextSpan(text: '', style: defaultStyle));
    } else {
      String text = tag.substring(1);
      spans.add(TextSpan(text: '@', style: defaultStyle));
      spans.add(TextSpan(text: text, style: tagStyle));
    }
    return RichText(
      text: TextSpan(children: spans),
    );
  },
),

Upvotes: 1

Related Questions