Changing text color if text contains hashtag "#"

Issue

Basically I want to achieve a “hashtag” feature.
I’m having a hard time making a logic wherein if the text contains a “#” (eg. I love #flutter), the #flutter text will change its color to blue.

Can you give me a hint on what widget to use or is there a package for this?

I can’t seem to find a similar problem.

Solution

With RichText you can create a text with different styles, where each text is a TextSpan, like this:

RichText(
  text: TextSpan(
    children: [
      TextSpan(text: "I love "),
      TextSpan(text: "#flutter", style: TextStyle(color: Colors.blue)),
    ],
  ),
)

You could take a String and create a list of texts and hashtags, then map that list checking: if the element contains # then use a TextSpan with color blue, otherwise use a default TextSpan.

Here is a quick working example, you could try to improve it:

RichText _convertHashtag(String text) {
  List<String> split = text.split(RegExp("#"));
  List<String> hashtags = split.getRange(1, split.length).fold([], (t, e) {
    var texts = e.split(" ");
    if (texts.length > 1) {
      return List.from(t)
        ..addAll(["#${texts.first}", "${e.substring(texts.first.length)}"]);
    }
    return List.from(t)..add("#${texts.first}");
  });
  return RichText(
    text: TextSpan(
      children: [TextSpan(text: split.first)]..addAll(hashtags
          .map((text) => text.contains("#")
              ? TextSpan(text: text, style: TextStyle(color: Colors.blue))
              : TextSpan(text: text))
          .toList()),
    ),
  );
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.indigo,
    appBar: AppBar(title: Text('#hashtag')),
    body: Center(
      child: _convertHashtag("I love #flutter and #android very much"),
    ),
  );
}

Answered By – Pablo Barrera

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.