Sub topic 6
Adding Custom Fonts
This chapter assumes you know basic Dart syntax, can create Flutter widgets, and have a working Flutter project. You should also know that pubspec.yaml configures project dependencies and assets.
A custom font is a font file that your app bundles instead of relying only on fonts installed on the device. Custom fonts help an app match a brand or improve readability. Flutter supports common font formats such as TrueType (.ttf) and OpenType (.otf).
Add font files to the project
Create a directory for fonts, then copy the font files into it:
my_app/
assets/
fonts/
Lora-Regular.ttf
Lora-Bold.ttf
lib/
main.dart
pubspec.yamlRegister the font family in pubspec.yaml:
flutter:
uses-material-design: true
fonts:
- family: Lora
fonts:
- asset: assets/fonts/Lora-Regular.ttf
- asset: assets/fonts/Lora-Bold.ttf
weight: 700The family value is the name Flutter uses in Dart. The weight value connects a file to a FontWeight. A regular file normally uses the default weight, 400. A bold file commonly uses 700.
Use spaces for YAML indentation. Do not use tabs. After changing pubspec.yaml, run flutter pub get, or let the IDE perform that step.
Use the font in a widget
Set fontFamily in a TextStyle:
import 'package:flutter/material.dart';
class FontExample extends StatelessWidget {
const FontExample({super.key});
@override
Widget build(BuildContext context) {
return const Text(
'Readable custom text',
style: TextStyle(
fontFamily: 'Lora',
fontSize: 24,
fontWeight: FontWeight.bold,
),
);
}
}When Flutter sees FontWeight.bold, it selects the registered 700 font file. If you request a weight that you did not register, Flutter may synthesize it or choose a nearby available weight. Register the weights your design actually uses to avoid unexpected results.
Apply the font through the theme
Setting the family on every widget duplicates configuration. A theme centralizes it:
MaterialApp(
theme: ThemeData(
fontFamily: 'Lora',
textTheme: const TextTheme(
bodyLarge: TextStyle(fontSize: 18),
headlineMedium: TextStyle(fontWeight: FontWeight.bold),
),
),
home: const FontExample(),
)A more targeted approach keeps the platform font for most text and changes selected styles:
final theme = ThemeData(
textTheme: const TextTheme(
headlineMedium: TextStyle(
fontFamily: 'Lora',
fontWeight: FontWeight.bold,
),
),
);Common errors and accessibility
A font that does not appear usually has a wrong path, family name, or YAML indentation. Stop and restart the app after adding or replacing font files if hot reload does not show the change.
Do not disable text scaling to preserve a fixed layout. Users may enlarge text for readability. Test your custom font at large text sizes and check that important content still wraps instead of disappearing.
Exercise
You registered Lora-Bold.ttf with weight 700. Which Dart style requests that file?
Show answer
Use TextStyle(fontFamily: 'Lora', fontWeight: FontWeight.w700) or FontWeight.bold.