Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 73 ยท Material, styling and assets

RichText, Text.rich and FittedBox

Mix styles and tappable links in one paragraph with Text.rich and TextSpan, embed widgets with WidgetSpan, and shrink text to fit with FittedBox.

A plain Text widget has one style. Real copy often needs more: a bold word in a sentence, a price with a small currency sign, "By continuing you accept the Terms" where the last two words are a link. For that you describe the text as a tree of spans, and Flutter lays it out as a single wrapping paragraph.

A second everyday problem is text that must fit a fixed space, such as a big score in a small tile or a button label in another language. FittedBox and a few Text settings handle that.

Real vs stand-in. The Dart is real and read-only, since the site cannot run Flutter. The live examples are JavaScript stand-ins of the two algorithms behind these widgets: style inheritance through a span tree, and the scale factor FittedBox computes.

Text.rich and TextSpan

Text.rich takes a TextSpan tree. A child span inherits the style of its parent and overrides only what it sets.

DART
Text.rich(
  TextSpan(
    style: const TextStyle(fontSize: 18, color: Colors.black87),
    children: [
      const TextSpan(text: 'Total: '),
      const TextSpan(
        text: '\$42',
        style: TextStyle(fontWeight: FontWeight.bold, color: Colors.green),
      ),
      const TextSpan(text: ' (incl. '),
      TextSpan(
        text: 'tax',
        style: const TextStyle(decoration: TextDecoration.underline),
      ),
      const TextSpan(text: ')'),
    ],
  ),
)

The root span's style comes from the surrounding DefaultTextStyle (so Text.rich picks up the theme), and every child merges on top. Use a \$ in Dart strings for a literal dollar sign. RichText is the lower-level widget that does the same job but does not read the DefaultTextStyle, so you must set a base color yourself or the text may come out in an unexpected default. Prefer Text.rich in almost all code.

Stand-in: how styles inherit

JS Flatten a span tree into styled runs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Tappable spans

A TextSpan can carry a gesture recognizer. The recognizer is an object that owns resources, so create it in a State and dispose it.

DART
class TermsText extends StatefulWidget {
  const TermsText({super.key});
  @override
  State<TermsText> createState() => _TermsTextState();
}

class _TermsTextState extends State<TermsText> {
  late final TapGestureRecognizer _terms = TapGestureRecognizer()
    ..onTap = () => Navigator.of(context).pushNamed('/terms');

  @override
  void dispose() {
    _terms.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final link = Theme.of(context).colorScheme.primary;
    return Text.rich(
      TextSpan(
        text: 'By continuing you accept the ',
        children: [
          TextSpan(
            text: 'Terms of Service',
            style: TextStyle(color: link, decoration: TextDecoration.underline),
            recognizer: _terms,
          ),
          const TextSpan(text: '.'),
        ],
      ),
    );
  }
}

Forgetting dispose leaks the recognizer. Tiny hit targets are an accessibility problem: pair inline links with larger buttons for important actions (accessibility). For text users should be able to copy, use SelectableText.rich. Flutter has no automatic "link detection", so a tap on a span works only because you attached a recognizer to it.

WidgetSpan: widgets inside text

WidgetSpan places any widget inline, so it flows and wraps with the words around it.

DART
Text.rich(
  TextSpan(
    children: [
      const TextSpan(text: 'Verified '),
      WidgetSpan(
        alignment: PlaceholderAlignment.middle,
        child: Icon(Icons.verified, size: 18, color: Colors.blue),
      ),
      const TextSpan(text: ' by the team'),
    ],
  ),
)

PlaceholderAlignment.middle centers the widget against the text line. Use baseline together with baseline: TextBaseline.alphabetic when a custom widget must sit on the baseline.

Fitting text into a space

Text already helps in two ways: maxLines with overflow: TextOverflow.ellipsis cuts long text with an ellipsis, and softWrap decides whether lines wrap. When you want the text to change size instead, wrap it in FittedBox.

DART
SizedBox(
  width: 80,
  height: 48,
  child: FittedBox(
    fit: BoxFit.scaleDown,   // shrink if too big, never enlarge
    child: Text(score.toString(), style: const TextStyle(fontSize: 40)),
  ),
)

FittedBox lays out its child at its natural size, then scales the child to fit the box according to fit. Common values are scaleDown (only shrink), contain (scale up or down, keep aspect ratio), fill (stretch, distorting text) and cover. alignment places the result inside the box. Because it scales a rendered painting rather than re-laying out the text, very large shrink factors make text look tiny, so test with long values.

For one line that must fit the width while staying readable, FittedBox is fine. For multi-line text that should grow and shrink between a minimum and maximum, use the auto_size_text package (AutoSizeText(text, maxLines: 2, minFontSize: 12)), which tries font sizes until the text fits. Also remember users can enlarge text in system settings (text scaling), and a shrunk label that ignores it can defeat their choice.

JS The scale FittedBox picks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • RichText without a base style. Text appears in the wrong color or size; use Text.rich.
  • Not disposing a recognizer. Create it in initState or as a late final field and dispose it.
  • FittedBox around a Text with unbounded width inside a Row. Constrain the parent first (constraints).
  • Hard-coding a shrink and ignoring accessibility. Allow reasonable text scaling and prefer wrapping to shrinking.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a TextSpan tree, what does a child span's style do?

    Children inherit from their parent span and override only what they define.
  2. 2. What must you do with a TapGestureRecognizer created for a TextSpan?

    Recognizers hold resources, so dispose them like controllers.
  3. 3. Which BoxFit makes FittedBox shrink its child when too big but never enlarge it?

    scaleDown only shrinks; contain also enlarges a small child to fill the box.
  4. 4. Why prefer Text.rich over RichText?

    RichText does not inherit the default text style; Text.rich does.

Summary

  • Text.rich with TextSpan mixes styles in one paragraph; children inherit from parents.
  • Attach a TapGestureRecognizer for links, and dispose it.
  • WidgetSpan puts widgets inline with text.
  • FittedBox(fit: BoxFit.scaleDown) shrinks text to fit a box; maxLines and overflow clip it instead.

Next: ClipRRect, ClipPath, ShaderMask and Opacity