Search code examples
stringlistfluttercolorstextspan

How can i dynamically change color of certain words of a paragraph in a Text Widget in flutter


Suppose you are given two Strings. One contains the words to be colored, and other contains the paragraph. example:

List words =["cow","milk","cattle" ];

String paragraph = "Cattle, or cows (female) and bulls (male), are large domesticated cloven-hooved herbivores. They are a prominent modern member of the subfamily Bovinae, are the most widespread species of the genus Bos, and are most commonly classified collectively as Bos taurus.";

I need those words in paragraph to be colored or linkable Text. help plz

Such As like the picture


Solution

  • Checkout Highlight Text. Here is a small example how you can achieve the effect you desired.

    Map<String, HighlightedWord> words = {
        "cow": HighlightedWord(
            textStyle: textStyle,
        ),
        "milk": HighlightedWord(
           
            textStyle: textStyle,
        ),
        "cattle": HighlightedWord(
           
            textStyle: textStyle,
        ),
    };
    

    Your Text

    TextHighlight(
        text: text, // Your text
        words: words, // Your highlighted words
    );