Sub topic 5
Registering a custom font family
This chapter covers the registration step only: how a font file becomes a named family that Flutter knows about. Applying that family to widgets and themes, and mapping weights and italics in detail, come in the next two chapters. Here we use a minimal widget to prove the registration works.
You should already be comfortable with these topics:
- Basic Dart syntax and a simple Flutter widget tree.
- Editing
pubspec.yamland runningflutter pub get. - YAML indentation rules, in particular that lists and nested maps depend on exact spaces.
- Declaring asset files and folders under
flutter: assets:, from the earlier chapters.
What registration means
A font file on disk is just a file. Flutter does not scan your project for fonts, and it does not read the internal name stored inside a .ttf file to decide what to call it. You tell Flutter three things in pubspec.yaml:
- A family name, which is the label your Dart code will use.
- Which files belong to that family.
- Which of those files is the bold one, the italic one, and so on.
At build time the Flutter tool copies the files into the app bundle and writes a manifest describing the families. At startup the engine reads that manifest. When a Text widget asks for fontFamily: 'Raleway', the engine finds the matching file by the family name, the requested weight, and the requested style.
Preparing the font files
Put the files inside the project. A common layout keeps fonts apart from images and data:
my_app/
pubspec.yaml
lib/
main.dart
assets/
fonts/
Raleway-Regular.ttf
Raleway-Bold.ttf
Raleway-Italic.ttfSome points about the files themselves:
- Use TrueType (
.ttf) or OpenType (.otf) files. Web-only formats such as.woffare not what Flutter expects, so convert them or download the desktop version of the font. - Each style of a family usually ships as its own file. Raleway, for example, has separate files for regular, bold, and italic.
- Check the license before you ship a font. Many free fonts allow embedding in apps, but some restrict it. The license file that comes with the font is the authority.
- The folder name
fontsis a convention. Flutter does not treat it specially, and you could useassets/typography/instead as long as the paths inpubspec.yamlmatch.
The fonts section
Fonts are declared under the flutter: key, as a sibling of assets: and not inside it. Here is the declaration from this tutorial's running example:
flutter:
assets:
- assets/images/
- assets/data/config.json
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: italicRead it from the outside in:
fonts:at theflutter:level is a list of families. Each list item starts with- family:.- Inside a family, a second
fonts:key holds the list of files for that family. The repeated name is confusing at first. The outer key is "all families", and the inner key is "the files in this one family". - Each file entry has a required
asset:path and two optional keys,weight:andstyle:.
The keys
| Key | Where | Required | Meaning |
|---|---|---|---|
| `family` | Family entry | Yes | The name Dart code uses in `fontFamily`. |
| `fonts` | Family entry | Yes | List of file entries for this family. |
| `asset` | File entry | Yes | Path to the font file, relative to the folder holding `pubspec.yaml`. |
| `weight` | File entry | No | An integer from 100 to 900 in steps of 100. Defaults to 400 (normal). |
| `style` | File entry | No | `normal` or `italic`. Defaults to `normal`. |
The weight values line up with Flutter's FontWeight constants: 100 is w100, 400 is w400 (the default normal), 700 is w700 (the default bold), and 900 is w900. Values such as 450 or 650 are not valid.
Indentation details that cause errors
The weight: and style: keys must align with asset:, not with the dash. In the example, weight: 700 sits two spaces to the right of the dash in - asset:, directly under the word asset. If you align it with the dash instead, YAML reads it as a malformed list item, and the tool reports an error.
A quick structural check:
- family:is indented insidefonts:.- The inner
fonts:aligns withfamily:, not with the dash before it. - Every
- asset:is indented inside the innerfonts:.
After editing, run flutter pub get. Flutter also re-reads pubspec.yaml when you run or build, but running pub get surfaces YAML mistakes early.
The family name is your label
The family: value is not looked up in the font file. If the file's internal name is "Raleway" and you write family: MyBrandFont, then fontFamily: 'MyBrandFont' works and fontFamily: 'Raleway' silently does not. Two consequences follow:
- You can rename a family without touching the files. This is handy when you want a semantic name such as
BodyFontthat you can repoint to another typeface later by editing onlypubspec.yaml. - Spelling and capitalization must match exactly.
ralewayandRalewayare different families to Flutter.
If the name in Dart does not match any registered family, Flutter does not throw. The text renders in a default font. Many "my font doesn't work" reports come down to this silent fallback.
Declaring more than one family
Add more entries to the outer list. Each family keeps its own files:
flutter:
uses-material-design: true
fonts:
- family: Raleway
fonts:
- asset: assets/fonts/Raleway-Regular.ttf
- asset: assets/fonts/Raleway-Bold.ttf
weight: 700
- family: RobotoMono
fonts:
- asset: assets/fonts/RobotoMono-Regular.ttfEach family is chosen independently. Declare only the files you actually use. Every extra file adds to your app size, which a later chapter covers.
One file or many files per family
A family with a single file is valid. If you register only Raleway-Regular.ttf and later ask for bold text, Flutter still uses that file and applies synthetic bolding, which the engine fakes by thickening the glyphs. The result is usually less attractive than a true bold design. The reverse applies to italic: the engine slants the regular glyphs, which often looks worse than a designed italic.
For quality typography, register one file per weight and style you plan to use. The next chapters show how Flutter picks among them.
Variable fonts, which pack many weights into one file, can also be registered as a single asset:. You then choose the axis values from Dart with fontVariations on TextStyle. That technique is outside this chapter's scope.
Verifying the registration
Don't wait until a screen looks wrong to find out whether a font was registered. The build produces a FontManifest.json in the asset bundle, and you can read it at runtime like any other asset. This program lists every registered family and renders one sample line in Raleway:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() => runApp(const FontCheckApp());
Future<List<String>> registeredFamilies() async {
final text = await rootBundle.loadString('FontManifest.json');
final entries = jsonDecode(text) as List<dynamic>;
return [
for (final entry in entries)
(entry as Map<String, dynamic>)['family'] as String,
];
}
class FontCheckApp extends StatelessWidget {
const FontCheckApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Font check')),
body: FutureBuilder<List<String>>(
future: registeredFamilies(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return ListView(
padding: const EdgeInsets.all(16),
children: [
const Text(
'Sample in Raleway',
style: TextStyle(fontFamily: 'Raleway', fontSize: 24),
),
const SizedBox(height: 16),
for (final family in snapshot.data!) Text(family),
],
);
},
),
),
);
}
}What you should see:
Ralewayappears in the list. If it does not, the declaration never reached the bundle, so look atpubspec.yaml.- Other families may appear too. With
uses-material-design: true,MaterialIconsis registered by the framework, and packages you depend on can add their own families. - The sample line looks like Raleway. If
Ralewayis listed but the sample looks like the default font, the family is registered but the file failed to load or the name used in code differs from the manifest.
The manifest has roughly this shape, which shows how your YAML keys map to JSON:
[
{
"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" }
]
}
]To also confirm the file bytes are in the bundle, load one directly. The call below fails with an exception if the path is wrong or the file is not bundled:
import 'package:flutter/services.dart' show rootBundle;
Future<int> fontFileSize() async {
final data = await rootBundle.load('assets/fonts/Raleway-Regular.ttf');
return data.lengthInBytes;
}Note that this only works because the font is also an asset in the bundle. You normally don't read font bytes yourself, since the engine does that.
Fonts and the assets list
The assets: list and the fonts: list are independent. A font file referenced under fonts: is bundled without being listed under assets:. You don't need to add assets/fonts/ to assets:, and doing so would only bundle the files a second time as plain assets. Likewise, a font file that sits in a listed asset folder but has no fonts: entry is bundled as a raw file and never becomes a usable family.
Changes require a restart
Hot reload does not pick up changes to pubspec.yaml. After adding or editing a font declaration:
- Run
flutter pub getif you edited dependencies, or at least save the file. - Stop the app and run it again with
flutter run, or use a full restart. Hot restart is often not enough for newly added files, so a full stop and start is the reliable choice.
If the font appears only after you stop and rerun the app, that confirms the bundle changed and the running instance had a stale one.
Common registration mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Text uses the default font, no error | Family name in Dart differs from `family:` in YAML | Match spelling and case exactly. |
| `pub get` reports a YAML error | `weight` or `style` indented at the wrong level | Align them under `asset:`. |
| Build error saying a font asset is missing | Wrong path or file not committed | Fix the path, which is relative to `pubspec.yaml`. |
| Font works on one platform only | Path case mismatch, such as `Raleway-bold.ttf` on a case-sensitive system | Match file name case exactly. |
| New font not visible after editing | Running instance has the old bundle | Stop and rerun the app. |
| Bold looks smeared | Only a regular file registered | Add a real bold file with `weight: 700`. |
| Weight like `weight: 600` appears to do nothing | No file with that weight exists, so Flutter picks the nearest | Register a file with that weight, or use values you have files for. |
Putting it together
A checklist for adding a new custom font:
- Download the font files and check the license.
- Copy them into
assets/fonts/(or a folder of your choice). - Add a
- family:entry underflutter: fonts:with one- asset:per file. - Add
weight:andstyle:to each file that is not regular. - Save, run
flutter pub get, and fully restart the app. - Confirm the family is in
FontManifest.jsonusing the check program above.
Exercise
A teammate writes this in pubspec.yaml and says the bold file is ignored. What is wrong, and how do you fix it? flutter: fonts: - family: Raleway fonts: - asset: assets/fonts/Raleway-Regular.ttf - asset: assets/fonts/Raleway-Bold.ttf - weight: 700
Show answer
The weight: 700 line is written as its own list item (- weight: 700) so it is not part of the bold file entry. The bold file has no weight and defaults to 400. Fix it by removing the dash and aligning weight: 700 under asset: in the bold entry, so the entry reads - asset: assets/fonts/Raleway-Bold.ttf followed by an indented weight: 700.
Exercise
Your pubspec.yaml declares family: BodyFont with files from Raleway, and your Dart code uses TextStyle(fontFamily: 'Raleway'). The text renders in the default font and Flutter reports no error. Why, and what are two ways to fix it?
Show answer
The family: value is a label you choose, and Flutter does not read the name inside the font file. Because no family named Raleway is registered, Flutter silently falls back to the default font. Fix it either by changing the Dart code to fontFamily: 'BodyFont', or by renaming the family in pubspec.yaml to Raleway. After a pubspec change, fully restart the app.
Exercise
You registered only Raleway-Regular.ttf under the family Raleway, and a widget asks for FontWeight.w700. What does Flutter do, and what should you change if the result looks poor?
Show answer
Flutter uses the only file available and has the engine synthesize a bold look by thickening the regular glyphs. The result is usually worse than a designed bold. To improve it, add Raleway-Bold.ttf to the family with weight: 700, then fully restart the app.