Member-only story
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 default styling, so you needed to set the rootTextSpan
style toDefaultTextStyle.of(context).style
in order to apply any styles inherited from the app theme. TheText.rich
constructor does this by default. Here is the same example again:
Text.rich(
TextSpan(
children: [
TextSpan(
text: 'multiple ',
style: TextStyle(color: Colors.red),
),
TextSpan(
text: 'styles',
style: TextStyle(color: Colors.blue),
),
],
),
),
That’s a little simpler and you don’t have to worry about forgetting about the app text theme, so I recommend you use Text.rich
rather than RichText
.
Style Quick Reference
The examples below demonstrate what’s possible with styling.
TextSpan(
text: 'text color',
style: TextStyle(color: Colors.green.shade700),
),
TextSpan(
text: 'background…