Quick reference and tutorial
Written for Flutter 3.7.
Every time I need to style text in Flutter, it always feels like reinventing the wheel. I’ve written about styled text before, but this will be a quick-reference article just related to using text spans.
Text vs RichText vs Text.rich
If your entire text uses the same style, you should use a Text
widget combined with a TextStyle
:
Text(
'single style',
style: TextStyle(color: Colors.deepPurple),
),
However, if you want substrings within your text to use different styles, use a RichText
widget with a tree of TextSpan
widgets:
RichText(
text: TextSpan(
style: DefaultTextStyle.of(context).style,
children: [
TextSpan(
text: 'multiple ',
style: TextStyle(color: Colors.red),
),
TextSpan(
text: 'styles',
style: TextStyle(color: Colors.blue),
),
],
),
),
Notes:
- Although you can make any sort of branching tree you like with
TextSpan
, the only sane way I know to create one is to have a single parentTextSpan
with a list of child spans that each include a substring with its accompanying style. RichText
doesn’t have any…