Sub topic 2
Declaring Files and Folders in pubspec.yaml
Flutter only packages files that you list in pubspec.yaml. A file in your project folder is not bundled just because it exists. This chapter covers the assets: list: its syntax, how a file entry differs from a folder entry, and the errors that come from getting it wrong.
This chapter assumes you can do four things:
- Read basic Dart.
- Build a simple widget tree.
- Edit
pubspec.yamland runflutter pub get. - Follow YAML indentation rules.
Loading assets at runtime, resolution variants, and fonts each get their own chapter. Here the focus is on declaring files and folders correctly.
Why a declaration is required
When you build an app, Flutter assembles an asset bundle. This is a packaged collection of files that ships inside the app and is read at runtime through an asset API. The build tool decides what goes into that bundle by reading pubspec.yaml. It does not scan your folders.
This has two consequences:
- A file missing from the list fails at runtime, not at compile time. The Dart code compiles fine and then throws when it asks for the file.
- Files you never reference but did declare still ship in the app and add to its size. The declaration list is a size budget as well as a configuration.
Where the assets section lives
Assets are declared under the top-level flutter: key. This key is a sibling of dependencies: and environment:. It is not nested inside either.
name: my_app
description: A sample app.
version: 1.0.0+1
environment:
sdk: ^3.5.0
dependencies:
flutter:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/
- assets/data/config.jsonThree details here cause most of the early mistakes:
- The
flutter:that appears underdependencies:is the SDK dependency. Theflutter:that holds assets is a separate top-level key. Having both is correct. assets:holds a YAML list. Every entry starts with-, and the entries are indented consistently underassets:.- YAML forbids tab characters for indentation. Use spaces. Two spaces per level is the convention, and it is what Flutter's templates use.
A second assets: key under the same flutter: block is also a mistake. Depending on the parser, you get an error or the later key silently replaces the earlier one. Put all entries in one list.
Declaring individual files
The simplest entry is the path of one file. The path is relative to the folder that contains pubspec.yaml, and it uses forward slashes on every operating system, Windows included.
flutter:
assets:
- assets/data/config.json
- assets/images/logo.pngEach listed file is bundled, and the path you write is the key you use at runtime. If you declare assets/data/config.json, your code asks for exactly 'assets/data/config.json'. Flutter does not strip the leading folder name or resolve it relative to anything else.
A file entry is precise. Nothing else is bundled except variants of that file, which later chapters cover. It is the right choice when you have a few files, or when a folder mixes files you need with files you do not.
Declaring directories
An entry that ends in / is a directory entry. It bundles every file directly inside that folder.
flutter:
assets:
- assets/images/The trailing slash is what tells Flutter the entry is a folder. Without it, assets/images is treated as a file path. Since no file has that name, the build fails.
Directory entries are not recursive
A directory entry covers only the files directly inside the folder. It does not include files in subfolders. Consider this project layout:
assets/
images/
logo.png
banner.jpg
icons/
home.png
settings.png
data/
config.jsonWith - assets/images/ declared, logo.png and banner.jpg are bundled. icons/home.png and icons/settings.png are not. To include them, add the subfolder as its own entry:
flutter:
assets:
- assets/images/
- assets/images/icons/
- assets/data/This is the most common cause of an asset that exists on disk but fails at runtime. When you add a new subfolder, add a new line.
Variant folders are the exception
Folders named like 2.0x and 3.0x, placed next to an image, hold resolution variants. Flutter picks these up automatically when you declare the base file or its folder. You do not list assets/images/2.0x/ yourself. The resolution-variants chapter covers how they are selected.
Choosing between file and directory entries
Neither form is better in every case. The choice is a trade-off between convenience and control.
| Form | Example | Includes | Best when | Risk |
|---|---|---|---|---|
| File entry | `assets/data/config.json` | One file, plus its variants | You have few files, or the folder mixes needed and unneeded files | Every new file needs a new line, and forgetting one fails at runtime |
| Directory entry | `assets/images/` | All files directly in the folder, plus variant subfolders | The folder holds only files the app uses | Unused files ship in the app and add to its size |
A workable convention is to use directory entries for folders you own and keep clean, such as assets/images/, and file entries for one-off files. Whatever you choose, keep the layout predictable. Group files by kind, such as assets/images/, assets/data/, and assets/audio/. Then each directory entry matches one purpose.
Path rules and limits
Several rules apply to every entry:
- Paths are relative to the project root, which is the folder holding
pubspec.yaml. Absolute paths and paths with..that leave the project are not what you want here. - Use forward slashes. A backslash path may work on a Windows machine and break on a CI server.
- The match is case-sensitive on the device. On Android,
Assets/Logo.pngandassets/logo.pngare different files. On macOS and Windows, your development filesystem may ignore case, so a wrong-case path can work in development and fail on a device. Match the on-disk name exactly. - Wildcards and globs such as
assets/**/*.pngare not supported. You list files or folders explicitly. - The
assets/folder name is a convention, not a requirement. You can use any folder name that fits your project, as long as the entry matches it. - Font files are declared under
fonts:, notassets:. If you put fonts inassets/fonts/, do not addassets/fonts/to the assets list. The font chapters cover the right declaration.
Map form and flavors
Each entry in the list can also be written as a map with a path key. This form lets you attach extra settings to an entry. In Flutter 3.22 and later, one of those settings is flavors. It limits an entry to builds of certain flavors, which are named build configurations such as development and production.
flutter:
assets:
- assets/common/
- path: assets/dev/
flavors:
- developmentHere assets/common/ is bundled in every build. assets/dev/ is bundled only when you build with --flavor development. Plain string entries and map entries can be mixed in one list. Most apps never need the map form, but it is a way to keep debug-only files out of release builds.
After you edit pubspec.yaml
Changes to the assets list are read by the build tooling, not by your running app. Three things follow:
- Save the file and run
flutter pub get. Most IDEs do this when you save. It validates the YAML and refreshes tool state. - Stop the app and run it again. Hot reload does not pick up new asset declarations. A new entry needs a fresh build. If an asset you just declared is still missing, a full restart is the first thing to try.
- Do a full rebuild when the problem persists. Running
flutter cleanfollowed byflutter pub getclears stale build output.
Checking what was bundled
You can ask the app which assets are in the bundle. Flutter builds a manifest, which is an index of every bundled asset, and the AssetManifest class reads it. A test can use this to catch declaration mistakes before anyone runs the app.
Save this as test/assets_test.dart:
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('declared assets are in the bundle', () async {
final manifest = await AssetManifest.loadFromAssetBundle(rootBundle);
final assets = manifest.listAssets();
expect(assets, contains('assets/data/config.json'));
expect(
assets.where((path) => path.startsWith('assets/images/')),
isNotEmpty,
);
});
}Run it with flutter test. The test passes when assets/data/config.json is declared and at least one file under assets/images/ is declared. If you remove an entry from pubspec.yaml, the test fails, which is the signal you want. Printing assets is also a quick way to see exactly which paths Flutter registered, including paths you did not expect.
Common errors
These are the failures you will see most often, with their causes:
No file or variants found for asset: assets/images/logo.pngappears at build time. The file entry points at a path that does not exist. Check the spelling, the case, and the folder.unable to find directory entry in pubspec.yamlappears at build time. A directory entry points at a folder that does not exist, or a folder entry was written for a path that is really a file.Unable to load asset: "assets/images/icons/home.png"appears at runtime. The build succeeded, so the entry list is valid, but this file is not covered. The usual cause is a subfolder that was never added as its own entry.- A YAML parse error on
pub getpoints at a line number. Look for a tab character, a list item indented at the wrong level, or a missing space after-. - An asset works on your Mac and fails on an Android device. Suspect a case mismatch between the path in code or YAML and the real file name.
A quick order for diagnosing: first confirm the path in the declaration matches the file on disk character for character, then confirm the path in your Dart code matches the declaration, then do a full restart. The troubleshooting chapter covers fonts and other failure modes in more detail.
Putting it together
This declaration covers the layout shown earlier. It bundles the top-level images, the icons subfolder, and one data file, and it leaves out everything else:
flutter:
uses-material-design: true
assets:
# Top-level images only; subfolders need their own lines.
- assets/images/
- assets/images/icons/
# A single file, so other files in assets/data stay out of the app.
- assets/data/config.jsonComments in YAML start with #. Using them to explain why an entry is a file and not a folder helps the next person who edits the list.
Exercise
Your project has assets/images/hero.png and assets/images/avatars/user1.png. pubspec.yaml lists only "- assets/images/". The app shows hero.png but throws "Unable to load asset" for user1.png. What is the cause, and what is the fix?
Show answer
A directory entry bundles only files directly inside the folder, not files in subfolders. Add "- assets/images/avatars/" to the assets list, then stop and rerun the app (a hot reload will not pick up the new entry).
Exercise
A teammate writes "- assets/data" (no trailing slash) to bundle every file in the assets/data folder. What happens, and how do you correct it?
Show answer
Flutter reads the entry as a single file path, finds no file named assets/data, and the build fails. Change it to "- assets/data/" so it is treated as a directory entry.
Exercise
An image loads on your macOS development machine but fails on an Android device. The file on disk is assets/images/Logo.png, and the code requests 'assets/images/logo.png'. Why does it differ between machines, and what do you change?
Show answer
Your development filesystem ignores case, so the wrong-case path happens to resolve there, but the bundle on Android matches names exactly. Make the declaration and the Dart path use the exact on-disk name, or rename the file to lowercase and update every reference.