问题
I have string which is like "Hi @username how are you" I want to change @username text to bold... just @username not whole sentence
Example : " Hi @username how are you
回答1:
This is a small function that would do that for you then returns a list of widgets.
List<Text> _transformWord(String word) {
List<String> name = word.split(' ');
List<Text> textWidgets = [];
for (int i = 0; i < name.length; i++) {
if (name[i].contains('@')) {
Text bold = Text(
name[i] + ' ',
style: TextStyle(
fontWeight: FontWeight.bold,
),
);
textWidgets.add(bold);
} else {
Text normal = Text(
name[i] + ' ',
);
textWidgets.add(normal);
}
}
return textWidgets;
}
You would call this function from a row widget
Row(
children: _transformWord(),
),
回答2:
Make use of flutter TextSpan
Text _myText;
/*set _myText.text to whatever text you want */
RichText(
text: TextSpan(
text: 'Hi',
style: DefaultTextStyle.of(context).style,
children: <TextSpan>[
TextSpan(text: _myText.text, style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(text: 'how are you')
],
),
)
来源:https://stackoverflow.com/questions/61252152/flutter-split-and-make-specific-word-bold