Sub topic 9
Fixing Missing Assets and Fonts That Do Not Render
This chapter assumes you can edit pubspec.yaml, run flutter pub get, and read a basic widget tree. It also assumes you have seen the earlier chapters on declaring assets, loading them with Image.asset and rootBundle, and registering font families. Here you learn to find out why a declared asset or font does not show up, and how to fix it.
Loud failures and silent failures
Assets and fonts fail in different ways, and the difference tells you where to look first.
- A missing asset fails loudly.
Image.assetreports an error, androotBundle.loadthrows aFlutterErrorwhose message starts withUnable to load asset. - A missing or misnamed font fails silently. Flutter does not report an error. It draws the text in the default font, so you only notice that the text looks wrong.
Build-time and runtime failures are different again. If pubspec.yaml names an explicit file that does not exist, the build stops with an error such as unable to locate asset entry in pubspec.yaml. If your Dart code asks for a path that was never declared, the build succeeds and the app fails at runtime.
Missing assets
Check the path and the indentation
Paths in pubspec.yaml are relative to the project root, the folder that holds pubspec.yaml. They are not relative to lib/. The string you pass to Image.asset or rootBundle.loadString must match the declared path exactly, including the extension.
YAML indentation causes most declaration problems. The assets: key must sit inside flutter:, indented by spaces. YAML does not allow tabs. Here the assets: key has lost its indentation:
flutter:
assets:
- assets/images/Here is the corrected version:
flutter:
assets:
- assets/images/The broken version is valid YAML, so flutter pub get does not complain. It just declares no assets, and every load fails at runtime. Check this first when nothing loads at all.
Directories are not recursive
Declaring a directory includes the files directly inside it. It does not include files in subdirectories. If home.png is at assets/images/icons/home.png, this entry does not cover it:
flutter:
assets:
- assets/images/Add the subdirectory as its own entry:
flutter:
assets:
- assets/images/
- assets/images/icons/Two details matter here:
- A directory entry must end with a slash.
- Resolution folders such as
2.0xand3.0xare the exception. Flutter finds them next to the base file without you declaring them.
Letter case
Android, Linux, and web servers treat Logo.png and logo.png as different files. macOS and Windows file systems usually do not, by default. So an asset with the wrong case can work on your desktop machine or iOS simulator and fail on an Android device. Match the case exactly everywhere, and prefer lowercase names with underscores.
Restart after editing pubspec
Hot reload does not apply changes to pubspec.yaml. After you add an asset entry or a font, run flutter pub get if your editor has not done it, then stop the app and run it again. A hot restart is not always enough for a new font. A full stop and run is the safe choice.
Look inside the bundle
When you cannot tell whether the problem is your declaration or your Dart code, ask the app what it actually contains. This widget lists every asset path in the bundle. AssetManifest.loadFromAssetBundle is available in Flutter 3.19 and later.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MaterialApp(home: AssetDoctor()));
class AssetDoctor extends StatelessWidget {
const AssetDoctor({super.key});
Future<List<String>> _listAssets() async {
final manifest = await AssetManifest.loadFromAssetBundle(rootBundle);
return manifest.listAssets();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Asset doctor')),
body: FutureBuilder<List<String>>(
future: _listAssets(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Manifest error: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return ListView(
children: [
for (final path in snapshot.data!) ListTile(title: Text(path)),
],
);
},
),
);
}
}If the path you want is not in the list, the problem is in pubspec.yaml. If it is in the list, the problem is the string in your Dart code.
You can also inspect the bundle from the command line. Run flutter build bundle, then open build/flutter_assets/. That folder holds your asset files, the asset manifest (AssetManifest.bin, or AssetManifest.json in older versions), and FontManifest.json, which lists the font families that were registered.
Handle failure in code
Show a fallback in the UI, and log the missing path, so a bad asset does not crash a screen.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
Future<String?> tryLoadText(String path) async {
try {
return await rootBundle.loadString(path);
} on FlutterError catch (e) {
debugPrint('Missing asset $path: ${e.message}');
return null;
}
}
class SafeLogo extends StatelessWidget {
const SafeLogo({super.key});
@override
Widget build(BuildContext context) {
return Image.asset(
'assets/images/logo.png',
width: 120,
errorBuilder: (context, error, stackTrace) =>
const Icon(Icons.broken_image, size: 48),
);
}
}errorBuilder also runs when the file exists but cannot be decoded. A zero-byte file, or a file saved with the wrong extension, hits this path. The message The asset does not exist or has empty data covers both cases.
An image that loads but is not visible
If there is no error but you see nothing, check the layout before the bundle:
- An image inside an unconstrained
Rowor a zero-height parent may have no size. Give it an explicitwidthandheight. - A transparent PNG on a dark background can look missing.
- On web, a very large image may fail to decode. Check the browser console.
Fonts that do not render
The family name must match
The family name you write in pubspec.yaml is the name you use in Dart. Flutter does not read the name stored inside the font file, so a file that your operating system calls "Raleway Medium" can be registered under any name you choose. Matching is exact and case-sensitive:
flutter:
fonts:
- family: Raleway
fonts:
- asset: assets/fonts/Raleway-Regular.ttfWith that declaration, TextStyle(fontFamily: 'raleway') finds nothing. Flutter quietly uses the default font. This is the most common font bug. It is easy to miss in a design that uses a font similar to the default.
Two other declaration mistakes look similar:
fonts:must sit underflutter:, at the same level asassets:. It is not a child ofassets:.- Each entry under a family's inner
fonts:list needs theasset:key. A bare path string is not accepted.
If a listed font file does not exist, the build fails with an asset entry error. That is a build-time failure, so it is easier to fix than a name mismatch.
Weights and styles
Say you declare only the regular file and then request bold:
const Text('Hello', style: TextStyle(fontWeight: FontWeight.w700));The text then appears in the regular weight, or in a synthesized bold that looks poor. The family needs a file mapped to weight 700:
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: italicKeep these rules in mind:
- The
weightvalue must be one of 100, 200, 300, 400, 500, 600, 700, 800, or 900. It matchesFontWeight.w100throughFontWeight.w900. - An entry with no
weightis treated as the normal weight, 400. styleacceptsitalicornormal. Italic text needsfontStyle: FontStyle.italicin theTextStyle.- If you request a weight you did not declare, Flutter typically picks the nearest declared weight instead of failing. This hides mistakes. Check the rendered result, not only the absence of errors.
Missing glyphs
Text may draw as empty boxes or as characters in a different font. Then the family is registered, but the font file does not contain those characters. A Latin-only font has no glyphs for Japanese, Arabic, or most emoji. Declare a second family that covers them and list it as a fallback:
flutter:
fonts:
- family: Raleway
fonts:
- asset: assets/fonts/Raleway-Regular.ttf
- family: NotoSansJP
fonts:
- asset: assets/fonts/NotoSansJP-Regular.ttfimport 'package:flutter/material.dart';
class MixedText extends StatelessWidget {
const MixedText({super.key});
@override
Widget build(BuildContext context) {
return const Text(
'Hello 日本語',
style: TextStyle(
fontFamily: 'Raleway',
fontFamilyFallback: ['NotoSansJP'],
),
);
}
}Flutter draws each character from the first family that has a glyph for it.
The theme does not apply everywhere
ThemeData(fontFamily: 'Raleway') sets the font for Material text styles. It does not reach every widget:
- A
TextStylethat sets its ownfontFamilyoverrides the theme. - Text that is not under a
MaterialApporThemeusesDefaultTextStyle, which does not know about your theme. This happens with a bareWidgetsAppor an overlay built outside the theme. - A
Textinside aCupertinoApptakes its font fromCupertinoThemeData, not fromThemeData.
To find which style a widget actually uses, wrap it in a Builder and print DefaultTextStyle.of(context).style.fontFamily.
Icons draw as boxes
Material icons are a font too. If Icons.home shows as a box, check that the flutter: section contains this line:
flutter:
uses-material-design: trueProjects created by flutter create include it, but it is easy to delete while editing the file.
Package assets and fonts
Assets that ship inside a package are bundled under a different path. An image declared in the my_icons package at assets/logo.png is stored in the app as packages/my_icons/assets/logo.png. These rules cover most problems:
- The package's own
pubspec.yamlmust declare the asset. The app does not redeclare it. The app only needs the package listed underdependencies. Image.asset('assets/logo.png', package: 'my_icons')loads it. Withoutpackage:, Flutter looks forassets/logo.pngin the app, and the load fails.- With
rootBundle, write the full path yourself:rootBundle.loadString('packages/my_icons/assets/data.json'). - The same rule applies inside the package's own widgets. Code inside
my_iconsthat loads its own assets must also passpackage: 'my_icons'. Otherwise it works in the package's example app and breaks when another app uses it. - For fonts, a family declared in the package is used with
TextStyle(fontFamily: 'Raleway', package: 'my_icons').
Use the AssetDoctor widget to confirm the real path. Package assets appear in its list with the packages/ prefix.
A symptom table
| Symptom | Likely cause | Fix |
|---|---|---|
| `Unable to load asset` for every file | `assets:` is not indented under `flutter:` | Correct the indentation and use spaces |
| One file in a subfolder is missing | Directory entries are not recursive | Add the subfolder with a trailing slash |
| Works on iOS, fails on Android | Letter case differs from the file name | Match the case exactly |
| New asset or font is not found | `pubspec.yaml` changes need a full run | Stop the app and run it again |
| Text is in the default font | The `fontFamily` string differs from the pubspec `family` | Use the exact name |
| Bold text looks regular | No file mapped to weight 700 | Add a `weight: 700` entry |
| Boxes instead of characters | The font lacks those glyphs | Add a font in `fontFamilyFallback` |
| Package image fails | `package:` argument is missing | Pass `package:` or use the `packages/` path |
Exercise
Your app declares - assets/images/ in pubspec.yaml. Image.asset('assets/images/icons/home.png') throws Unable to load asset, and the file exists at that path. What is wrong, and what is the fix?
Show answer
A directory entry only includes files directly inside it, not files in subdirectories. Add - assets/images/icons/ (with the trailing slash) to the assets: list, then stop the app and run it again.
Exercise
A widget uses TextStyle(fontFamily: 'raleway'), but pubspec.yaml registers the family as Raleway. The app shows no error. What do users see, and why is there no error?
Show answer
They see the text in the default font. Family names are matched exactly and case-sensitively, and an unknown family is not treated as an error. Flutter falls back to the default font silently. Change the string to Raleway.
Exercise
Your package my_icons declares assets/logo.png. The app depends on the package, but Image.asset('assets/logo.png') fails. Write the corrected call, and give the path you would use with rootBundle.
Show answer
Use Image.asset('assets/logo.png', package: 'my_icons'). With rootBundle, the path is packages/my_icons/assets/logo.png.