Sub topic 2
Styling text with TextStyle
This chapter assumes you can write a StatelessWidget, know Dart named parameters, and have already shown text with the Text widget. It covers TextStyle, the class that controls how text looks: size, weight, color, spacing, and decoration. It also covers how styles merge, since that is the source of most styling bugs.
What TextStyle is
TextStyle is an immutable object that describes how a run of text is painted. Every field is nullable. A field that is null means "no opinion here, inherit from somewhere else." That one rule explains most of Flutter's text styling behavior.
You pass a TextStyle to the style parameter of Text:
import 'package:flutter/material.dart';
class StyledTitle extends StatelessWidget {
const StyledTitle({super.key});
@override
Widget build(BuildContext context) {
return const Text(
'Quarterly report',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
color: Colors.indigo,
letterSpacing: 0.5,
),
);
}
}Because TextStyle has a const constructor, you can mark the whole Text as const when every value is a compile-time constant. That avoids rebuilding the object on every build.
Commonly used properties
| Property | Type | Effect |
|---|---|---|
| `fontSize` | `double` | Size in logical pixels. Scaled by the user's font setting. |
| `fontWeight` | `FontWeight` | `w100` to `w900`. `FontWeight.bold` is `w700`. |
| `fontStyle` | `FontStyle` | `normal` or `italic`. |
| `color` | `Color` | Glyph color. |
| `letterSpacing` | `double` | Extra space between letters, in logical pixels. |
| `wordSpacing` | `double` | Extra space between words. |
| `height` | `double` | Line height as a multiple of `fontSize`, not a pixel value. |
| `decoration` | `TextDecoration` | `underline`, `lineThrough`, `overline`, or `none`. |
| `fontFamily` | `String` | Name of a registered font family. |
| `backgroundColor` | `Color` | Fill behind the glyphs. |
Two of these are frequently misread. fontSize is in logical pixels, which are device-independent, so 16 looks about the same physical size on screens of different density. height is a multiplier: height: 1.5 on a 16-pixel font gives a 24-pixel line box.
Weight, italics, and decoration
FontWeight values map to the weights a font file provides. If the font has no file for the weight you request, Flutter picks the nearest available one, or synthesizes bold for some fonts. For predictable results with a custom font, register the weights you use (see the chapter on custom fonts).
Decoration needs a bit more care. A decoration has a line type, a style, and a color:
import 'package:flutter/material.dart';
class OldPrice extends StatelessWidget {
const OldPrice({super.key});
@override
Widget build(BuildContext context) {
return const Text(
'USD 59',
style: TextStyle(
decoration: TextDecoration.lineThrough,
decorationColor: Colors.red,
decorationStyle: TextDecorationStyle.solid,
decorationThickness: 2,
color: Colors.grey,
),
);
}
}To combine lines, use TextDecoration.combine([TextDecoration.underline, TextDecoration.overline]).
How styles are resolved
A Text widget does not paint with only the style you give it. It builds its final style from layers:
- The ambient
DefaultTextStylefound above it in the widget tree. AScaffold,Material,AppBar, and buttons each set their own. - The
styleyou pass toText, merged on top of that.
Merging means your non-null fields replace the inherited ones, and your null fields leave the inherited ones alone. So Text('Hi', style: TextStyle(fontWeight: FontWeight.bold)) is bold, but its size and color still come from the surrounding DefaultTextStyle.
You can set an inherited style for a whole subtree with DefaultTextStyle:
import 'package:flutter/material.dart';
class Notes extends StatelessWidget {
const Notes({super.key});
@override
Widget build(BuildContext context) {
return const DefaultTextStyle(
style: TextStyle(fontSize: 14, color: Colors.black87),
child: Column(
children: [
Text('First note'),
Text('Second note'),
Text(
'Important note',
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
);
}
}All three lines are 14 pixels and dark gray. The last is also bold.
Changing a style with copyWith
Because TextStyle is immutable, you do not modify one. You create a modified copy with copyWith, which returns a new style where only the named fields differ:
import 'package:flutter/material.dart';
class Greeting extends StatelessWidget {
const Greeting({super.key});
@override
Widget build(BuildContext context) {
return Text(
'Hello, Flutter',
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
}Here the base style comes from the theme, and only the weight changes. The ?. is needed because the theme's style slots are nullable. If the slot is null, the whole expression is null, and Text falls back to the inherited style. The next chapters cover themes and layout in detail.
The inherit flag
Each TextStyle has an inherit field, which defaults to true. When true, the style merges with the inherited style as described above. When false, the style is used as given, and any null field takes a framework default instead of an inherited value. A style with inherit: false and no fontSize renders at the default size of 14, not at the size of the surrounding text.
Leave inherit alone unless you need a style that is fully independent of its context. One related gotcha: interpolating between two styles with different inherit values, as happens in some animations, can fail an assertion in debug mode.
Common errors
- Yellow double underline under text. The text has no
MaterialorDefaultTextStyleancestor, usually because it sits outside aScaffoldorMaterial. Wrap it in aScaffold, aMaterial, or aDefaultTextStyle. heightlooks wrong. You treated it as pixels. It is a multiplier offontSize.- Bold has no effect with a custom font. The font family has no bold file registered. Add a
weight: 700entry inpubspec.yaml. - Color changes are ignored. A parent such as
ElevatedButtonorListTilesupplies its own style, and your style is applied on a different widget than you expected. Style theTextchild directly. - Style looks different on each screen. You hard-coded sizes in many places. Prefer one shared style source, covered in the theme chapter.
Putting it together
The following widget shows a product label. It uses a theme base, one override, and a decoration, and it limits itself to two lines:
import 'package:flutter/material.dart';
class ProductLabel extends StatelessWidget {
const ProductLabel({super.key, required this.name, required this.oldPrice});
final String name;
final String oldPrice;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
Text(
oldPrice,
style: textTheme.bodySmall?.copyWith(
decoration: TextDecoration.lineThrough,
),
),
],
);
}
}Exercise
A Text widget inside a DefaultTextStyle(style: TextStyle(fontSize: 14, color: Colors.black87)) has style: TextStyle(fontWeight: FontWeight.bold). What size and color does it render with, and why? What changes if the Text's style also sets inherit: false?
Show answer
It renders at size 14 in black87, bold. Fields that are null in the Text's style are inherited from the DefaultTextStyle, and only fontWeight is replaced. With inherit: false, the style is not merged with the ancestor, so the null fontSize and color fall back to framework defaults (size 14 by default, but the color no longer comes from the ancestor), and only the bold weight is kept from your style.
Exercise
You want a 16-pixel font with 24-pixel lines. What value do you give height, and what would happen if you passed 24?
Show answer
Use height: 1.5, because height multiplies fontSize (16 x 1.5 = 24). Passing 24 would make each line 384 pixels tall (16 x 24), leaving huge gaps between lines.