I have a text from API, but I want to format it to be bold before displayed to the screen.
Here is the code
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
state.listExplanation[index].description!, --> this is the text that I want to format
style: body1(),
),
The variable description that I call has API text like this:
"description" : "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s."
Nah, before it be displayed to the screen, I want to make only "Lorem Ipsum" and "1500s" to be bold. I only know how to change the text entirely, but to change the text partially, it makes me confuse.
I hope you can give me your advice.
3
Answers
If the text is coming from an
API
, you can still use the same approach by splitting the text into parts, formatting the parts you want to be bold, and then combining them back together.Try this example:
We split the text into parts using the
split()
method, and then loop through each part to determine if it should be formatted as bold. If the part matches the criteria, we create aTextSpan
with thefontWeight
property set tobold
. If the part doesn’t match, we create aTextSpan
without any special formatting. Finally, we combine all theTextSpan
‘s back together using aRichText
widget.you can ask your backend developers to return you the text in html format and then use flutter_widget_from_html
Suggestions:
You should look out for
RichText
Here it is not clear what is the regex you want to follow from the
description
from the api, Is it , First two words and last word bold ? , If yes you should write proper regex and split the string accordingly.Sample Code: