How to Use Custom Fonts in Flutter: Step-by-Step Guide
To use custom fonts in Flutter, add your font files to a folder like
assets/fonts, declare them in pubspec.yaml under fonts, and then apply the font family in your TextStyle. This lets you style text with your chosen fonts easily.Syntax
To use custom fonts in Flutter, you need to:
- Add font files to your project folder (e.g.,
assets/fonts/). - Declare the fonts in
pubspec.yamlunder thefontssection. - Use the font family name in your Flutter widgets via
TextStyle(fontFamily: 'YourFontName').
yaml
flutter:
fonts:
- family: YourFontName
fonts:
- asset: assets/fonts/YourFontFile.ttfExample
This example shows how to add a custom font called RobotoMono and use it in a Text widget.
dart
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Custom Font Example')), body: const Center( child: Text( 'Hello with RobotoMono!', style: TextStyle(fontFamily: 'RobotoMono', fontSize: 24), ), ), ), ); } }
Output
A screen with an app bar titled 'Custom Font Example' and centered text 'Hello with RobotoMono!' displayed in the RobotoMono font.
Common Pitfalls
Common mistakes when using custom fonts in Flutter include:
- Not declaring the font files correctly in
pubspec.yaml(wrong indentation or path). - Forgetting to run
flutter pub getafter editingpubspec.yaml. - Using the wrong font family name in
TextStyle(it must match thefamilyname declared). - Not adding the font files to the project folder or missing them in version control.
yaml
Wrong pubspec.yaml snippet:
flutter:
fonts:
- family: RobotoMono
fonts:
- asset: assets/fonts/RobotoMono.ttf
Correct pubspec.yaml snippet:
flutter:
fonts:
- family: RobotoMono
fonts:
- asset: assets/fonts/RobotoMono.ttfQuick Reference
| Step | Description |
|---|---|
| 1. Add font files | Place .ttf or .otf files in assets/fonts/ folder |
| 2. Declare fonts | Edit pubspec.yaml under flutter > fonts with family and asset path |
| 3. Run pub get | Run flutter pub get to update dependencies |
| 4. Use font | Apply fontFamily in TextStyle in your widgets |
Key Takeaways
Add your font files to a folder inside your Flutter project, usually assets/fonts.
Declare fonts properly in pubspec.yaml with correct indentation and paths.
Use the declared font family name exactly in TextStyle to apply the custom font.
Run flutter pub get after editing pubspec.yaml to load the fonts.
Check for typos and missing files if the font does not appear as expected.