Sub topic 8
Using Assets and Fonts That Ship in Packages
Prerequisites
This chapter assumes you can already:
- Declare assets and font families in an app's
pubspec.yaml. - Load images with
Image.assetand text withrootBundle.loadString. - Apply a font through
TextStyleandThemeData. - Add a dependency to
pubspec.yaml, including apath:dependency, and runflutter pub get.
Everything here builds on those steps. The new part is that a package's files live under a different path than your app's own files, and you must tell Flutter which package to look in.
Why a package needs its own path
Flutter bundles all assets into one archive and looks each file up by a string key. In an app, the key is the path you wrote in pubspec.yaml, such as assets/images/logo.png.
A package can have a file with the same path. Two packages might each contain assets/logo.png. If keys had no package information, one would overwrite the other.
Flutter avoids this by adding a prefix to every package asset:
packages/<package_name>/<path inside the package>Your app's own assets have no prefix. Package assets always have one.
The package argument on Image.asset, AssetImage, and TextStyle builds this prefixed key for you. If you leave it out, Flutter looks up the plain key, and the lookup fails for anything that lives in a package.
How a package declares its assets
A package declares assets in its own pubspec.yaml, using the same flutter: section an app uses. Paths are relative to the package root, not to the app.
Suppose a package named my_icons has this layout:
my_icons/
pubspec.yaml
assets/
logo.png
2.0x/logo.png
data/icons.json
fonts/
Raleway-Regular.ttf
Raleway-Bold.ttf
lib/
my_icons.dartIts pubspec.yaml lists what it ships:
name: my_icons
description: Icons, a logo and a font shared across apps.
version: 0.1.0
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.10.0"
dependencies:
flutter:
sdk: flutter
flutter:
assets:
- assets/logo.png
- assets/data/icons.json
fonts:
- family: Raleway
fonts:
- asset: fonts/Raleway-Regular.ttf
- asset: fonts/Raleway-Bold.ttf
weight: 700The consuming app only needs my_icons in its dependencies. It does not have to repeat these entries. When the app builds, Flutter reads the flutter: section of every package the app depends on and bundles what each one declares. This also applies to packages the app depends on indirectly. If the app uses package A and A depends on B, B's declared assets are bundled too.
Declaring assets/logo.png also bundles the 2.0x/ and 3.0x/ variants next to it, as it does in an app. Resolution selection works the same way for package images.
Where the prefixed key comes from
The key depends on where the file sits in the package:
| File location in the package | Declared in the package pubspec as | Bundle key |
|---|---|---|
| `my_icons/assets/logo.png` | `assets/logo.png` | `packages/my_icons/assets/logo.png` |
| `my_icons/lib/icons/heart.png` | `lib/icons/heart.png` | `packages/my_icons/icons/heart.png` |
Files under lib/ lose the lib/ part of the key, because Dart already treats lib/ as the public root of a package (package:my_icons/... maps to lib/). Files outside lib/ keep their full relative path. If you remember only one rule, remember this one, because most wrong-key errors come from forgetting it.
Loading a package image
To show the logo from my_icons in an app, pass the package name:
import 'package:flutter/material.dart';
Widget packageLogo() {
return Image.asset(
'assets/logo.png',
package: 'my_icons',
);
}Image.asset combines the two arguments into packages/my_icons/assets/logo.png. The path you pass is the one from the package's own layout, and the package argument supplies the prefix.
AssetImage takes the same argument. Use it wherever an ImageProvider is needed, for example in a DecorationImage:
import 'package:flutter/material.dart';
Widget packageBackground() {
return Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/logo.png', package: 'my_icons'),
fit: BoxFit.contain,
),
),
);
}Loading text and JSON from a package
rootBundle.loadString and rootBundle.load have no package argument. They take the final key as a plain string, so you write the prefix yourself:
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
Future<Map<String, dynamic>> loadIconTable() async {
final text = await rootBundle.loadString(
'packages/my_icons/assets/data/icons.json',
);
return jsonDecode(text) as Map<String, dynamic>;
}A package that wants to hide this detail can export a helper. The package author writes the key once, and apps call a normal function:
// my_icons/lib/my_icons.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
const String _package = 'my_icons';
/// The logo that ships with this package.
class MyIconsLogo extends StatelessWidget {
const MyIconsLogo({super.key, this.width = 120});
final double width;
@override
Widget build(BuildContext context) {
return Image.asset(
'assets/logo.png',
package: _package,
width: width,
);
}
}
/// Reads the icon table bundled with this package.
Future<Map<String, dynamic>> loadIconTable() async {
final text = await rootBundle.loadString(
'packages/$_package/assets/data/icons.json',
);
return jsonDecode(text) as Map<String, dynamic>;
}This is the pattern to follow when you write a package. Code inside the package must also pass package: 'my_icons'. At runtime that code runs inside the consuming app, and the app's bundle is the one searched. A plain Image.asset('assets/logo.png') inside the package works in the package's own example app only if the example happens to have the same file. In any other app, the lookup fails.
Assets that are not declared by the package
A package can keep files under lib/ without declaring them in its own pubspec.yaml. These files are not bundled automatically. The app decides which ones to include by listing the prefixed key in its own pubspec.yaml:
flutter:
assets:
- packages/my_icons/icons/heart.png
- packages/my_icons/icons/star.pngNote the key has no lib/ in it, following the table above. Use this when a package offers a large library of files and the app needs only a few. A package that declares all of them forces every app to carry all of them.
An asset-path entry ending in / includes every file in that folder, but not its subfolders. That rule applies to package keys too.
Fonts in packages
A package declares a font family the same way an app does. The only difference is how the app refers to it. Flutter registers a package font under the name packages/<package_name>/<family>, so the family Raleway from my_icons becomes packages/my_icons/Raleway.
Applying a package font to one widget
TextStyle has a package argument that adds the prefix for you:
import 'package:flutter/material.dart';
class PackageFontDemo extends StatelessWidget {
const PackageFontDemo({super.key});
@override
Widget build(BuildContext context) {
return const Text(
'Hello, package fonts',
style: TextStyle(
fontFamily: 'Raleway',
package: 'my_icons',
fontWeight: FontWeight.w700,
),
);
}
}This selects Raleway-Bold.ttf from the package, because the package declared that file with weight: 700. Writing fontFamily: 'packages/my_icons/Raleway' and leaving out package has the same effect.
Do not pass both. With package set, Flutter adds the prefix itself, so a full packages/... name would be prefixed twice and the font would not be found.
Applying a package font to the whole app
ThemeData accepts package as well:
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(
theme: ThemeData(
fontFamily: 'Raleway',
package: 'my_icons',
),
home: const Scaffold(
body: Center(
child: Text('Themed with a package font'),
),
),
);
}
}Every Text that uses the theme's text styles now renders in the package's Raleway. Text with an explicit fontFamily in its own TextStyle still overrides it.
Package widgets and their fonts
If a package widget sets its own font, it must use package as well, for the same reason as images:
import 'package:flutter/material.dart';
class BrandTitle extends StatelessWidget {
const BrandTitle(this.text, {super.key});
final String text;
@override
Widget build(BuildContext context) {
return Text(
text,
style: const TextStyle(
fontFamily: 'Raleway',
package: 'my_icons',
fontWeight: FontWeight.w700,
),
);
}
}Without package, the widget works in the package's example app and then silently falls back to the default font in every other app.
Fonts stored under lib/
Font files placed in a package's lib/ folder are not bundled automatically, just like images. The app picks the files it wants and adds them to a family it declares itself, using the prefixed key:
flutter:
fonts:
- family: Raleway
fonts:
- asset: assets/fonts/Raleway-Regular.ttf
- asset: packages/my_icons/fonts/Raleway-Medium.ttf
weight: 500Here Raleway-Medium.ttf lives at my_icons/lib/fonts/. The family belongs to the app, so you use it with no package argument: TextStyle(fontFamily: 'Raleway', fontWeight: FontWeight.w500). This lets an app mix its own files and package files in one family.
Quick reference
| You want to load | Use | Key or argument |
|---|---|---|
| A package image in a widget | `Image.asset(path, package: 'pkg')` | `package` argument |
| A package image as a provider | `AssetImage(path, package: 'pkg')` | `package` argument |
| A package text or JSON file | `rootBundle.loadString(key)` | `'packages/pkg/path'` |
| A package font on one widget | `TextStyle(fontFamily: 'F', package: 'pkg')` | `package` argument |
| A package font app-wide | `ThemeData(fontFamily: 'F', package: 'pkg')` | `package` argument |
| A `lib/` file the package did not declare | App `pubspec.yaml` entry | `packages/pkg/path-without-lib` |
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Unable to load asset: "assets/logo.png"` | Missing `package` argument, so Flutter searched the app's own assets | Add `package: 'my_icons'` |
| `Unable to load asset: "packages/my_icons/lib/icons/heart.png"` | `lib/` included in the key | Remove `lib/` from the key |
| Package asset missing after a pubspec change | Hot reload does not re-read assets | Run `flutter pub get`, then stop and fully restart the app |
| Asset exists in the package folder but is not found | The package did not declare it and the app did not either | Declare it in the package, or list the `packages/...` key in the app |
| Text falls back to the default font | `package` left out, or the family name differs from the declaration | Match `family:` exactly and pass `package` |
| Font works in the package example app only | The package widget omits `package` | Add `package: 'my_icons'` inside the package's own code |
If an asset still does not load, check the AssetManifest.json listing in the built bundle to see which keys exist. Comparing the key your code builds against that list usually shows the mismatch at once.
Pitfalls worth knowing
- Assets are not tree-shaken. Everything a dependency declares is bundled whether your app uses it or not. A package that declares a large image folder adds its full size to your app. Check
pubspec.yamlin a package before adding it, and prefer packages that leave optional files underlib/for the app to choose. - Name collisions are avoided on purpose. The app's
assets/logo.pngand the package'sassets/logo.pngare different keys, so both can exist. Which one loads depends only on thepackageargument. - Family names are per package. Two packages can each declare a family called
Raleway. They stay separate because each is registered under its ownpackages/<name>/prefix. - Path dependencies behave the same. A package referenced with
path: ../my_iconsis bundled the same way as one from pub.dev. This makes a local package a convenient place to test the setup.
Exercise
A package named brand_kit has the file brand_kit/lib/images/hero.png. The package's own pubspec does not declare it. What must the app's pubspec.yaml contain to bundle it, and how does the app then show it?
Show answer
The app's pubspec.yaml must list packages/brand_kit/images/hero.png under flutter: assets:. The key has no lib/ part. The app then calls Image.asset('images/hero.png', package: 'brand_kit').
Exercise
An app depends on my_icons. A widget uses Text('Hi', style: TextStyle(fontFamily: 'Raleway')) and shows the default font, although my_icons declares the Raleway family. Give two ways to fix it.
Show answer
Add the package argument: TextStyle(fontFamily: 'Raleway', package: 'my_icons'). Or write the full name instead: TextStyle(fontFamily: 'packages/my_icons/Raleway'). Use only one of the two, since combining them adds the prefix twice.
Exercise
How do you read a JSON file declared as assets/data/icons.json in the package my_icons, and why does rootBundle.loadString not need a package argument?
Show answer
Call rootBundle.loadString('packages/my_icons/assets/data/icons.json'). rootBundle takes the final bundle key as a plain string, so you write the packages/<name>/ prefix yourself. Image.asset and TextStyle build that prefix from their package argument.