Sub topic 5
Mixing styles with Text.rich
This chapter assumes you can write a StatelessWidget, know that Text takes a style argument, and have used Theme.of(context).textTheme. It also assumes you know what a StatefulWidget lifecycle (initState and dispose) is.
A plain Text widget applies one TextStyle to its whole string. That is not enough for a sentence like "Total: USD 42", where one word is bold, or for a line of legal text that contains a tappable link. Text.rich solves this. It renders one paragraph built from a tree of styled pieces.
The span tree
Text.rich takes an InlineSpan instead of a String. The span you will use most is TextSpan. It has three main parts:
textis the string for this span. It is optional.styleis aTextStylefor this span and its children.childrenis a list of more spans, drawn aftertext.
const Text.rich(
TextSpan(
text: 'Total: ',
children: [
TextSpan(
text: 'USD 42',
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
)The root span draws "Total: " in the default style. The child draws "USD 42" in bold. Both pieces sit in the same paragraph, so they wrap together, align together, and obey one maxLines limit.
How styles are inherited
A span does not replace its parent's style. It merges with it. Any property you leave null in a child comes from the parent. Flutter resolves the final style from the top down:
DefaultTextStylefrom the nearest ancestor (theScaffoldandThemeset this up for you).- The
styleargument ofText.richitself. - The
styleof the rootTextSpan. - The
styleof each nestedTextSpan.
This means you only state what differs. The example below sets a shared color and size once on Text.rich. Only the price changes weight.
import 'package:flutter/material.dart';
class PriceLine extends StatelessWidget {
const PriceLine({super.key});
@override
Widget build(BuildContext context) {
return Text.rich(
const TextSpan(
text: 'Total: ',
children: [
TextSpan(
text: 'USD 42',
style: TextStyle(fontWeight: FontWeight.bold),
),
TextSpan(
text: ' (tax included)',
style: TextStyle(fontSize: 12),
),
],
),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontSize: 18,
),
);
}
}Here "USD 42" is 18 logical pixels, bold, in the surface color. The tax note is 12 pixels but keeps the same color.
Combining with theme styles
To start from a theme style, pass it as the Text.rich style and only add differences in the spans. You can also call copyWith on a theme style inside a span, such as Theme.of(context).textTheme.titleLarge?.copyWith(...). In that case the span style replaces the inherited properties that the theme style defines.
Making part of the text tappable
TextSpan has a recognizer property. Assign a TapGestureRecognizer to it and that span responds to taps, while the rest of the paragraph does not.
A recognizer holds resources, so you must dispose of it. That is why this widget is stateful. Creating a recognizer inside build leaks one on every rebuild.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
class TermsNotice extends StatefulWidget {
const TermsNotice({super.key});
@override
State<TermsNotice> createState() => _TermsNoticeState();
}
class _TermsNoticeState extends State<TermsNotice> {
late final TapGestureRecognizer _tap;
@override
void initState() {
super.initState();
_tap = TapGestureRecognizer()
..onTap = () {
debugPrint('Terms of Service tapped');
};
}
@override
void dispose() {
_tap.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final linkStyle = TextStyle(
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
);
return Text.rich(
TextSpan(
text: 'By continuing you accept the ',
children: [
TextSpan(
text: 'Terms of Service',
style: linkStyle,
recognizer: _tap,
),
const TextSpan(text: '.'),
],
),
);
}
}Notice that the outer TextSpan is not const. A recognizer is created at runtime, so any span that holds one cannot be a compile-time constant. The const on the final period span is still allowed.
Placing widgets inside text with WidgetSpan
WidgetSpan embeds any widget in the flow of a paragraph. It is useful for an icon next to a word that must wrap together with the text.
import 'package:flutter/material.dart';
class RatingLine extends StatelessWidget {
const RatingLine({super.key});
@override
Widget build(BuildContext context) {
return Text.rich(
TextSpan(
text: 'Rating: 4.8 ',
children: const [
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Icon(Icons.star, size: 16, color: Colors.amber),
),
TextSpan(text: ' (120 reviews)'),
],
),
);
}
}PlaceholderAlignment.middle centers the icon against the text line. The default, bottom, often makes an icon look too low. A WidgetSpan is treated as one unbreakable character, so it never splits across lines.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Span text is black in dark mode | A span sets its own `color` and ignores the theme | Take the color from `Theme.of(context)` or leave it `null` |
| Link does nothing on tap | `recognizer` was set on the root span, but the text is in a child, or the recognizer was disposed | Attach it to the span that holds the text, and dispose only in `dispose()` |
| "Memory leak" or "recognizer not disposed" warnings | `TapGestureRecognizer` created in `build` | Create it in `initState` and call `dispose()` |
| Compile error: not a constant expression | `const` placed on a span that contains a recognizer | Remove `const` from that span and its ancestors |
| Mixed text is hard to select | `Text.rich` is not selectable | Use `SelectableText.rich` with the same span tree |
| Icon sits below the baseline | Default `WidgetSpan` alignment | Set `alignment: PlaceholderAlignment.middle` |
Choosing between Text and Text.rich
Use plain Text when the whole string shares one style. Use Text.rich when styles differ inside one sentence. Do not build the same effect with a Row of several Text widgets. A Row will not wrap the pieces as one paragraph, it can overflow, and screen readers read each piece as a separate item.
Text scaling also applies to the whole span tree. When a user enlarges system fonts, every span grows, so keep an eye on WidgetSpan content such as fixed-size icons, which may not grow with the text.
Exercise
A Text.rich has style: TextStyle(fontSize: 20, color: Colors.black). Its root TextSpan has a child span with style: TextStyle(fontWeight: FontWeight.bold). What size and color does the child text have, and why? Then explain why a TapGestureRecognizer should not be created inside build.
Show answer
The child is 20 pixels, black, and bold. A child span merges with its parent's style, so properties the child leaves null (size and color) come from the ancestors, and only the weight is overridden. A recognizer created in build is created again on every rebuild, and each old one is never disposed, which leaks resources. Create it once in initState and call dispose() on it in the state's dispose.