Sub topic 4
Using Theme Text Styles
Assume you know basic Dart syntax, StatelessWidget, the build method, and how a Flutter project uses MaterialApp. This chapter explains how to use a theme’s text styles instead of choosing separate font sizes and colors throughout an app.
A text theme is a named collection of TextStyle objects. Names such as headlineMedium, titleLarge, bodyLarge, and labelLarge describe the role of text in the interface. The theme can change these styles for the whole app.
Reading a text style from the theme
Use Theme.of(context).textTheme inside build. The returned style may be nullable, so use ?. when calling a method such as copyWith.
import 'package:flutter/material.dart';
class ProfileHeader extends StatelessWidget {
const ProfileHeader({super.key});
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Maya Chen',
style: textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
'Product designer',
style: textTheme.bodyLarge,
),
],
);
}
}headlineMedium supplies the theme’s font family, size, weight, color, and spacing for a headline. copyWith changes only the properties you provide. In this example, the headline becomes bold while keeping the other theme values.
Use a semantic role that matches the content. A page title usually needs a headline style. Supporting information usually needs a body style. A button label usually needs a label style.
Theme changes and local overrides
The same widget automatically responds when the app’s theme changes. For example, a dark theme can provide light text colors without requiring every Text widget to change.
You can define the text theme in MaterialApp:
MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo),
textTheme: const TextTheme(
headlineMedium: TextStyle(fontSize: 28),
bodyLarge: TextStyle(fontSize: 18),
),
),
home: const ProfileHeader(),
)A local TextStyle override is appropriate for a special case, such as bolding one word or applying a warning color. Avoid setting fontSize and color directly on every text widget. Those values become difficult to update consistently.
The text theme and layout
Theme styles affect layout. Larger fonts require more width and height. User text scaling can increase them further. Do not assume that a themed style will always fit on one line. Combine the style with layout rules such as maxLines, overflow, or a flexible parent when needed.
Exercise
Exercise
Why should a widget use textTheme.bodyLarge instead of defining its own font size and color?
Show answer
It keeps the widget consistent with the app theme and lets global theme or accessibility changes apply without editing the widget.