Sub topic 6
Using fonts in a widget and in the app theme
This chapter assumes you have already declared a font family in pubspec.yaml, run flutter pub get, and restarted the app. The family used here is Raleway, with regular, bold, and italic files. You should be comfortable reading a Flutter widget tree and know what BuildContext is.
Declaring a font only makes the files available. Nothing changes on screen until some TextStyle asks for the family by name. This chapter covers the three places you can do that, how they combine, and what to check when the result looks wrong.
The family name is the link
The family: value in pubspec.yaml is the string you pass as fontFamily in Dart. It does not need to match the name stored inside the .ttf file. It only has to match between the two places you write it, including capitalization.
flutter:
fonts:
- family: Raleway
fonts:
- asset: assets/fonts/Raleway-Regular.ttf
- asset: assets/fonts/Raleway-Bold.ttf
weight: 700
- asset: assets/fonts/Raleway-Italic.ttf
style: italicIn Dart, 'Raleway' now refers to that group of three files. A typo such as 'raleway' does not raise an error. Flutter silently falls back to the platform default font. This silent fallback is behind most "my font does not work" reports.
Three levels of control
A piece of text gets its final style from several layers. From most specific to least specific:
- The
styleyou pass to aTextwidget. - The nearest
DefaultTextStyleabove the widget in the tree. - The
ThemeDataof the nearestTheme, which supplies the text styles that Material widgets put intoDefaultTextStyle.
| Level | Where you set it | Scope | Typical use |
|---|---|---|---|
| Single widget | `Text(style: TextStyle(fontFamily: ...))` | One `Text` | A logo line or a one-off display title |
| Subtree | `DefaultTextStyle.merge` or a nested `Theme` | Everything below that widget | A card, a dialog, a code panel |
| Whole app | `ThemeData(fontFamily: ...)` or `textTheme` | Every Material widget | The main brand font |
The sections below follow this order.
Styling a single widget
Pass a TextStyle with fontFamily to one Text:
import 'package:flutter/material.dart';
class Headline extends StatelessWidget {
const Headline({super.key});
@override
Widget build(BuildContext context) {
return const Text(
'Spring Sale',
style: TextStyle(
fontFamily: 'Raleway',
fontSize: 32,
fontWeight: FontWeight.w700,
),
);
}
}Because fontWeight is w700 and the family declares a file with weight: 700, Flutter picks Raleway-Bold.ttf. FontWeight.bold is the same value as FontWeight.w700, so either spelling works.
This approach is fine for an exception. If you repeat fontFamily: 'Raleway' in dozens of places, a typo in one of them gives you an inconsistent screen. A theme avoids that.
Setting the font for the whole app
ThemeData has a fontFamily argument. It applies the family to the default text styles that Material widgets use: AppBar titles, buttons, list tiles, text fields, dialogs, and the body text of a Scaffold.
import 'package:flutter/material.dart';
void main() => runApp(const App());
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fonts',
theme: ThemeData(fontFamily: 'Raleway'),
home: const Scaffold(
body: Center(
child: Text(
'Hello, fonts',
style: TextStyle(fontWeight: FontWeight.w700),
),
),
),
);
}
}The Text here never names a family. It inherits Raleway through the theme, and only changes the weight. This is the usual pattern: set the family once, then vary size, weight, and style where needed.
What the theme does not cover
- Icons.
Iconwidgets draw glyphs from theMaterialIconsfont or another icon font. SettingfontFamilyon the theme does not change them, and an icon never switches to Raleway. - Text outside a Material ancestor. A
Textplaced outside aScaffold,Material, or similar widget does not receive the theme's text style. In debug builds it appears with a yellow double underline, which is Flutter's visual warning. Wrap it in aMaterialor aScaffold, or give it an explicit style. - Cupertino widgets. A
CupertinoAppusesCupertinoThemeDataandCupertinoTextThemeData, notThemeData. If you useMaterialApp, the Material theme applies. If you mix in Cupertino widgets, check that they pick up your family.
Using the text theme for roles
Material defines named text roles such as displayLarge, headlineMedium, titleLarge, bodyMedium, and labelLarge. Each role has a size, weight, and spacing. Reading a role through Theme.of(context).textTheme keeps your screens consistent with the theme.
import 'package:flutter/material.dart';
void main() => runApp(const FontDemoApp());
class FontDemoApp extends StatelessWidget {
const FontDemoApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Font demo',
theme: ThemeData(
fontFamily: 'Raleway',
textTheme: const TextTheme(
headlineMedium: TextStyle(
fontWeight: FontWeight.w700,
letterSpacing: 0.5,
),
),
),
home: const FontDemoPage(),
);
}
}
class FontDemoPage extends StatelessWidget {
const FontDemoPage({super.key});
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(title: const Text('Fonts')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Theme headline', style: textTheme.headlineMedium),
const SizedBox(height: 12),
const Text('Body text uses bodyMedium from the theme.'),
const SizedBox(height: 12),
const Text(
'Italic override',
style: TextStyle(fontStyle: FontStyle.italic),
),
const SizedBox(height: 12),
Text(
'Larger bold body',
style: textTheme.bodyMedium?.copyWith(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
}Points to notice in this example:
- The
textThemeyou pass toThemeDatais merged into the default text theme. You only list the roles you want to change. The other roles keep their defaults, and they still useRalewayfromfontFamily. - The
headlineMediumoverride sets only a weight and letter spacing. It does not repeat the family, because the merge keepsRaleway. - Role styles are nullable.
textTheme.bodyMediumhas typeTextStyle?, so you write?.copyWith(...). Passing a null style toTextis allowed and means "use the inherited style". copyWithreturns a new style. It never changes the theme.
Using different families for different roles
You can give headings a different family from body text. Declare both families in pubspec.yaml, then set fontFamily on individual roles:
ThemeData(
fontFamily: 'Raleway',
textTheme: const TextTheme(
displayLarge: TextStyle(fontFamily: 'Playfair'),
headlineMedium: TextStyle(fontFamily: 'Playfair'),
),
)Here Playfair is an example family name. It works only if you have declared a family with that exact name and supplied its files. Roles you do not mention use Raleway. Keep the number of families small, usually one or two, because each one adds files to the app.
Styling a subtree
Sometimes one area of the screen needs a different font, such as a code sample in a mostly Raleway app. Declare the second family first:
flutter:
fonts:
- family: Raleway
fonts:
- asset: assets/fonts/Raleway-Regular.ttf
- asset: assets/fonts/Raleway-Bold.ttf
weight: 700
- asset: assets/fonts/Raleway-Italic.ttf
style: italic
- family: RobotoMono
fonts:
- asset: assets/fonts/RobotoMono-Regular.ttfYou need to add RobotoMono-Regular.ttf to assets/fonts/ yourself. If the file is missing, the build fails at asset bundling time, not at runtime.
There are two ways to apply it to a group of widgets. DefaultTextStyle.merge changes the inherited style for everything below it:
import 'package:flutter/material.dart';
class CodePanel extends StatelessWidget {
const CodePanel({super.key});
@override
Widget build(BuildContext context) {
return DefaultTextStyle.merge(
style: const TextStyle(fontFamily: 'RobotoMono', fontSize: 14),
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('final a = 1;'),
Text('final b = 2;'),
],
),
);
}
}A nested Theme changes the text theme for every Material role below it, which is useful when the subtree contains buttons or text fields:
import 'package:flutter/material.dart';
class MonoSection extends StatelessWidget {
const MonoSection({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
final base = Theme.of(context);
return Theme(
data: base.copyWith(
textTheme: base.textTheme.apply(fontFamily: 'RobotoMono'),
),
child: child,
);
}
}TextTheme.apply returns a copy of the whole text theme with the family replaced in every role. Use DefaultTextStyle.merge for plain Text widgets, and a nested Theme when Material widgets are involved.
Weight and style selection in practice
When a style asks for a weight and style, Flutter looks in the family for the declared file that matches. These requests map to the earlier Raleway declaration as follows:
| Request in code | File used |
|---|---|
| No weight, no style (defaults to `w400`, normal) | `Raleway-Regular.ttf` |
| `fontWeight: FontWeight.w700` | `Raleway-Bold.ttf` |
| `fontStyle: FontStyle.italic` | `Raleway-Italic.ttf` |
| `w700` and italic together | Bold if available, otherwise italic; no bold italic file exists, so the engine may synthesize it |
If you ask for a weight or style that no file declares, Flutter does not report an error. It uses the nearest match, and the platform may synthesize a faux bold or slant. Synthesized glyphs look slightly off compared with real design files. If you need bold italic, declare a file with both weight: 700 and style: italic. Mapping weights to files is covered in more detail in the next chapter.
Fallback fonts
A font may lack some characters, such as emoji or non-Latin scripts. Flutter then looks for the glyph in other fonts. You can control the order with fontFamilyFallback, which is available on TextStyle and on ThemeData:
ThemeData(
fontFamily: 'Raleway',
fontFamilyFallback: const ['NotoSansJP', 'sans-serif'],
)NotoSansJP must be a family you have declared. The platform fonts that Flutter reaches through its default fallback are used only after your list. If characters appear as empty boxes, the glyph is missing from every font in the chain.
Checking that it works
When a font does not appear, check these in order:
- Restart fully. Changes to
pubspec.yamlare not applied by hot reload or hot restart. Stop the app and run it again. - Run
flutter pub get. Editors often do this on save, but not always. - Compare names. The
family:value and the Dart string must match exactly. - Check paths and indentation. Each
asset:path must exist, relative to the project root. A mis-indentedweight:orstyle:is ignored or causes a parse error. - Confirm the widget is under a theme. A
Textoutside Material does not inherit your family. - Test with a distinct font. A font close to the platform default is hard to tell apart. Temporarily switch to a decorative family to confirm that the pipeline works.
Common mistakes
- Declaring the font under the wrong key, for example inside
assets:instead offonts:. Declaring a font file as a plain asset does not register it as a font. - Setting
fontFamilyinThemeDatabut passing aTexta fullTextStylewithinherit: false. That style ignores all inherited values, including the family. - Expecting
Iconto change with the theme font. - Declaring many weights and using only two. Each file is bundled and increases app size.
Exercise
Your app has theme: ThemeData(fontFamily: 'Raleway'). A Text widget that sits in a Scaffold body shows Raleway, but a Text in a custom widget placed directly under runApp shows a yellow double underline and not Raleway. Why does this happen, and how do you fix it?
Show answer
The first Text is under a Scaffold, which includes a Material that sets the DefaultTextStyle from the theme's text theme. The second Text has no Material ancestor, so it has no theme-based default style, and Flutter's debug fallback shows the underline. Fix it by wrapping the widget in a Material or Scaffold, or by placing it under a MaterialApp. As a last resort, give the Text an explicit TextStyle(fontFamily: 'Raleway').
Exercise
Write the ThemeData that makes the whole app use Raleway, and makes titleLarge bold with 0.2 extra letter spacing without repeating the family name.
Show answer
ThemeData(fontFamily: 'Raleway', textTheme: const TextTheme(titleLarge: TextStyle(fontWeight: FontWeight.w700, letterSpacing: 0.2))). The textTheme is merged into the defaults, and the titleLarge style keeps the Raleway family supplied by fontFamily.
Exercise
You change Raleway-Bold.ttf to a new file in pubspec.yaml and hot reload the app, but the old bold glyphs still appear. What should you do?
Show answer
Stop the app and run it again. Hot reload and hot restart do not reload font declarations from pubspec.yaml, so a full restart is required after running flutter pub get.