Sub topic 4
Using theme text styles
This chapter assumes you can write a StatelessWidget, you know how Text and TextStyle work, and you have a Flutter project that uses MaterialApp. It covers how to take text styles from the app's theme instead of hard-coding them in each widget.
Why use theme text styles
A style such as TextStyle(fontSize: 24, fontWeight: FontWeight.bold) copied across forty screens is hard to change. A theme holds a named set of styles in one place. Widgets ask for a style by role, for example "a headline", and the theme decides what that looks like. Changing the theme changes the whole app, including light and dark variants.
The TextTheme and the Material type scale
ThemeData has a textTheme property of type TextTheme. A TextTheme is a collection of 15 named TextStyle values, the Material type scale:
| Group | Names | Typical use |
|---|---|---|
| Display | `displayLarge`, `displayMedium`, `displaySmall` | Very large, short text such as hero numbers |
| Headline | `headlineLarge`, `headlineMedium`, `headlineSmall` | Screen and section headings |
| Title | `titleLarge`, `titleMedium`, `titleSmall` | App bar titles, list item titles |
| Body | `bodyLarge`, `bodyMedium`, `bodySmall` | Paragraphs and general content |
| Label | `labelLarge`, `labelMedium`, `labelSmall` | Buttons, captions, small annotations |
Choose a style by its role, not by its size. If a heading should look different, change headlineMedium in the theme. Do not edit the font size on each screen.
Reading a style from the theme
Call Theme.of(context) to get the nearest ThemeData, then read a style from its textTheme.
import 'package:flutter/material.dart';
class SectionTitle extends StatelessWidget {
const SectionTitle(this.text, {super.key});
final String text;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Text(text, style: textTheme.titleLarge);
}
}Each style in a TextTheme has the type TextStyle?. It is nullable, because a custom TextTheme may leave some entries unset. Passing it straight to Text(style: ...) is fine, since style accepts null. To call copyWith on it you need ?., as in the first topic example: textTheme.headlineMedium?.copyWith(...). Avoid ! unless you control the theme, because a missing entry would then throw at runtime.
Adjusting a style with copyWith
copyWith returns a new TextStyle with only the fields you name changed. Everything else comes from the theme, so the text still follows size and font changes made there.
Text(
'Overdue',
style: Theme.of(context).textTheme.labelLarge?.copyWith(
color: Theme.of(context).colorScheme.error,
),
)Take colors from Theme.of(context).colorScheme rather than from Colors.red. Then the color adapts to dark mode and to a different seed color.
Defining the theme
Set the styles you want to change in MaterialApp.theme. The example below is a complete app.
import 'package:flutter/material.dart';
void main() => runApp(const ThemedApp());
class ThemedApp extends StatelessWidget {
const ThemedApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
useMaterial3: true,
colorSchemeSeed: Colors.teal,
textTheme: const TextTheme(
headlineMedium: TextStyle(
fontWeight: FontWeight.w700,
letterSpacing: -0.5,
),
bodyMedium: TextStyle(height: 1.4),
),
),
home: const ArticlePage(),
);
}
}
class ArticlePage extends StatelessWidget {
const ArticlePage({super.key});
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(title: const Text('Article')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Theme-driven text', style: textTheme.headlineMedium),
const SizedBox(height: 8),
Text(
'Every style here comes from the theme, so one edit '
'in ThemeData restyles the whole screen.',
style: textTheme.bodyMedium,
),
],
),
),
);
}
}The TextTheme you pass to ThemeData is merged over the default Material typography. headlineMedium keeps the default font size and only gains the bold weight and letter spacing. The other 13 styles are untouched.
Where theme text comes from
You do not have to write style: on every Text. A Text with no style, or a style that leaves fields unset, takes the rest from the nearest DefaultTextStyle above it. Material widgets such as Scaffold, Card, and ListTile set their own DefaultTextStyle from the theme, usually bodyMedium.
A TextStyle has an inherit flag, which is true by default. When it is true, the style's unset fields are filled in from the DefaultTextStyle. This is why TextStyle(fontWeight: FontWeight.bold) alone still gets the right size and color.
If you set inherit: false, the style stands alone. Any field you leave out falls back to a bare default, which can look like a large white or yellow-underlined text in a place where you did not expect it. Leave inherit alone unless you need that behavior.
Changing many styles at once
TextTheme.apply changes every style in the theme in one call. It is the right tool for a font family or a base color that applies to the whole app.
final base = ThemeData(useMaterial3: true).textTheme;
final theme = ThemeData(
useMaterial3: true,
textTheme: base.apply(
fontFamily: 'Lora',
bodyColor: Colors.grey.shade900,
displayColor: Colors.black,
),
);bodyColor covers body, title, and label styles. displayColor covers display and headline styles. For a font alone, ThemeData(fontFamily: 'Lora') is shorter. The Lora family must be registered in pubspec.yaml, which a later chapter covers.
Scoped overrides and common errors
To restyle one part of the tree, wrap it in a Theme widget built from the current theme with copyWith. Widgets below it see the changed ThemeData.
Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.apply(bodyColor: Colors.white),
),
child: const Text('Light text for a dark banner'),
)These mistakes are common:
- Calling
Theme.of(context)in the widget that createsMaterialApp. Thatcontextsits above the theme, so it returns a default theme. Read it from a child widget, or wrap the call in aBuilder. - Reading the theme outside
build. Do not cacheTheme.of(context)in a field. Call it insidebuildso the widget rebuilds when the theme changes. - Hard-coding sizes next to theme styles. Passing
fontSize: 18incopyWithkeeps working, but it hides that role from the theme. Prefer changing the theme, or choose a different role. - Expecting a color in the theme to survive dark mode. A fixed
Colors.blackin your lightTextThemestays black in the dark theme. Leave color unset and let the default typography choose it, or define it per theme.
Exercise
A Text uses style: TextStyle(color: Colors.red) inside a Card. The text is red but the size matches the card's body text. Why, and what would change if you added inherit: false?
Show answer
With inherit: true (the default), the style's unset fields come from the nearest DefaultTextStyle, which the Material widgets set from the theme, so size, font, and weight are inherited and only the color is overridden. With inherit: false, none of those values are inherited. The text would use Flutter's bare defaults for size and font, so it would look different from the surrounding text.
Exercise
You want every headlineMedium in the app to be bold, and one warning message to use labelLarge in the theme's error color. Which two pieces of code do you write, and where?
Show answer
In MaterialApp.theme, pass ThemeData(textTheme: const TextTheme(headlineMedium: TextStyle(fontWeight: FontWeight.bold))). At the warning message, write Text(message, style: Theme.of(context).textTheme.labelLarge?.copyWith(color: Theme.of(context).colorScheme.error)).