Sub topic 1
What counts as an asset and how Flutter bundles it
Every Flutter app ships with more than compiled Dart code. Logos, JSON configuration, sound clips and font files have to travel with the app and be readable at runtime. Flutter calls the files you add this way assets. This chapter explains what qualifies as an asset, what happens to an asset at build time, where it ends up on each platform, and how your code reaches it. The next chapters cover the exact pubspec.yaml syntax, image variants and fonts in detail.
Prerequisites
This chapter assumes you already have the following:
- Basic Dart syntax, including
async/awaitandFuture. - Experience building a simple Flutter widget tree with
StatelessWidgetandMaterialApp. - The ability to edit
pubspec.yamland runflutter pub get. - Familiarity with YAML indentation rules. Two-space indentation matters, and list items start with
-.
What counts as an asset
An asset is a file that is packaged into your app at build time and can be read by your code at runtime. Flutter copies it into the app bundle byte for byte. It does not interpret or transform the file, with one exception covered later (asset transformers).
Typical assets include:
- Images such as PNG, JPEG, WebP, GIF and SVG files. SVG needs a rendering package, because
Image.assetcannot decode it. - Text and data files such as JSON, YAML, CSV, plain text and license text.
- Binary data such as audio, video, ML models, shaders and database seed files.
- Font files such as
.ttfand.otf. Fonts are a special case. You declare them in their ownfonts:section, not theassets:list, and Flutter registers them with the text engine.
Several things that look like assets are not Flutter assets:
| Item | Why it is not a Flutter asset |
|---|---|
| Dart source files | The compiler turns them into the app's machine code (or JavaScript on web). They are not bundled as files. |
| Android `res/` resources and iOS `Assets.xcassets` | The native build tools package these. Native code reads them, for example the app icon and launch screen. Dart code cannot reach them through `rootBundle`. |
| Files the user downloads or your app creates | They are created after install, so they live in the device file system. |
| Files in your project that are not listed in `pubspec.yaml` | Flutter does not scan your project folders. Only what you declare is bundled. |
The last row is the most common source of confusion. Putting a file in an assets/ folder does nothing by itself. The folder name is only a convention.
Assets are read-only
The bundle is part of the installed app, so your app cannot write to it, rename files in it or delete from it. If you need a file that changes (user settings, a cache, a downloaded update), keep a copy elsewhere. A common pattern is to ship a seed file as an asset, copy it into the app's documents directory on first launch (the path_provider package finds that directory), and edit the copy from then on.
How bundling works
You describe the assets, and the Flutter build tool does the packaging. The flow is the same on every platform.
The steps are:
- Declare. Under
flutter:inpubspec.yaml, you list each file or directory inassets:. - Resolve. When you run
flutter runorflutter build, the tool reads the list, expands directories into the files they contain and checks that every declared path exists. A path that does not exist stops the build with an error. This early failure is useful, because a typo in the file name is caught immediately. - Assemble. The tool copies the files into a directory named
flutter_assetsand writes some bookkeeping files next to them. These includeAssetManifest.bin(a list of every asset and its variants),FontManifest.json(the registered font families) and a file of third-party license notices. Older Flutter versions also wroteAssetManifest.json. - Package. The platform-specific build step places
flutter_assetsinside the app. The Flutter engine knows where to find it. - Read. At runtime,
rootBundleand widgets such asImage.assetask the engine for a file by its key. The key is the path string exactly as written inpubspec.yaml, for exampleassets/images/logo.png.
Where the bundle ends up
| Platform | Location of `flutter_assets` |
|---|---|
| Android | Inside the APK or AAB, under `assets/flutter_assets/` |
| iOS | Inside `App.framework` in the app's `Frameworks` folder |
| macOS | Inside `App.framework` in the app's `Contents/Frameworks` folder |
| Windows and Linux | A `data/flutter_assets` folder next to the executable |
| Web | An `assets/` folder in `build/web`, served over HTTP |
On the web, assets are not local files. They are fetched from the server when first needed. Because the bundle folder is itself named assets, an asset with the key assets/images/logo.png is served at the URL path assets/assets/images/logo.png. This looks like a bug when you first see it in the browser's network tab, but it is expected.
You rarely need these locations. They matter when you inspect a build to confirm that a file was or was not included. You can unzip an APK and look for assets/flutter_assets/. You can also list the build output of a web build with ls build/web/assets.
A minimal declaration
Here is a project layout with a small set of assets:
my_app/
pubspec.yaml
lib/
main.dart
assets/
images/
logo.png
data/
config.json
greeting.txtThe matching section of pubspec.yaml:
name: my_app
description: Asset basics demo.
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/
- assets/data/config.json
- assets/data/greeting.txtPoints to notice:
- Paths are relative to the folder that holds
pubspec.yaml, never tolib/. - A path ending in
/declares a directory. Flutter bundles the files directly inside it. It does not bundle files in subdirectories, so a nested folder needs its own line. The chapter on declaring assets covers this rule and its one exception in detail. - A path without a trailing slash declares one file.
- The
assets:list sits underflutter:, at the same indentation level asuses-material-design. Putting it at the top level of the file, or indenting it too far, is a common mistake that produces either a pub error or a silent failure to bundle.
After you change pubspec.yaml, run flutter pub get (most editors do this on save). A hot reload does not re-read the asset list. Stop the app and run it again so the bundle is rebuilt.
Reading what was bundled
Reading the manifest at runtime is a direct way to see exactly what Flutter bundled. This is useful when you are unsure whether a declaration worked. The following app lists every asset key in the bundle:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show AssetManifest, rootBundle;
void main() {
runApp(const ManifestApp());
}
class ManifestApp extends StatelessWidget {
const ManifestApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Bundled assets')),
body: FutureBuilder<List<String>>(
future: _listAssets(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
final keys = snapshot.data!;
return ListView(
children: [for (final key in keys) ListTile(title: Text(key))],
);
},
),
),
);
}
}
Future<List<String>> _listAssets() async {
final manifest = await AssetManifest.loadFromAssetBundle(rootBundle);
return manifest.listAssets();
}With the declaration above, the list shows assets/data/config.json, assets/data/greeting.txt and assets/images/logo.png. It also lists assets that come from packages and from Flutter itself, such as packages/cupertino_icons/assets/CupertinoIcons.ttf if you depend on that package. If a file you expected is missing, the declaration is wrong. That is a faster test than searching for the cause inside an image widget.
Reading an asset by key
Every asset access goes through an AssetBundle. rootBundle is the global bundle for the app, and DefaultAssetBundle.of(context) returns the bundle for a widget subtree. The default is rootBundle, but tests or embedded content can substitute another. Use rootBundle in plain functions and DefaultAssetBundle.of(context) in widgets when you want that flexibility.
The bundle offers three main reads:
loadString(key)returns the file decoded as UTF-8 text.load(key)returns the raw bytes asByteData. Use it for audio, binary formats and anything that is not text.loadStructuredData<T>(key, parser)loads a string, runs your parser and caches the parsed result.
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/services.dart' show rootBundle;
Future<String> readGreeting() {
return rootBundle.loadString('assets/data/greeting.txt');
}
Future<Map<String, dynamic>> readConfig() async {
final text = await rootBundle.loadString('assets/data/config.json');
return jsonDecode(text) as Map<String, dynamic>;
}
Future<Uint8List> readLogoBytes() async {
final data = await rootBundle.load('assets/images/logo.png');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
}Images usually do not need this code. Image.asset('assets/images/logo.png') builds an AssetImage, which asks the bundle for the bytes, decodes them and caches the decoded image. The next chapters cover these calls in detail. What matters here is that the string is a lookup key, not a file system path. You cannot pass it to File(...) from dart:io, because on Android the bundle is inside a compressed archive and there is no file at that path.
Loading is asynchronous
All bundle reads return a Future, even though the data is local. On the web the read is a network request, and on mobile it goes through the engine. Two consequences follow:
- Do not call
rootBundle.loadStringinsidebuildwithout caching the result. Calling it on every rebuild repeats the work. Load once ininitState, in aFutureBuilderwhose future is stored in state, or in a service object created at startup. - Raw
rootBundlereads cache nothing forloadandloadString. In release mode,loadStructuredDatacaches its parsed results. If you read the same large file repeatedly, keep the result yourself.
What goes wrong at the bundling boundary
Most asset problems come from a mismatch between three things: the file on disk, the string in pubspec.yaml and the string in Dart. The runtime error Unable to load asset: "..." means the key was not found in the bundle. The common causes are:
- The file is not listed, or its directory entry lacks a trailing slash.
- The file sits in a subdirectory of a declared directory.
- The path differs in letter case. File systems on Windows and macOS often ignore case, but the bundle lookup does not, so a mismatch that works in development can fail on Android.
- The YAML is mis-indented, so
assets:is not read as part offlutter:. - You changed
pubspec.yamland only hot reloaded.
The chapter on troubleshooting works through these failures with diagnostic steps. For now, remember that the manifest listing above is the quickest check.
Keeping the bundle intentional
Everything you declare is shipped in every build, whether or not the code uses it. A directory entry such as assets/images/ is convenient, but it also includes any stray file someone drops into that folder, such as a 6 MB source image. The set of bundled files therefore needs to be reviewed like any other part of the codebase. The final chapter covers size in detail. The habit to build now is to declare directories that hold only shipping files, and to keep working files (design sources, raw recordings) outside the declared folders.
Summary of the model
- An asset is a file you declare in
pubspec.yaml. Flutter copies it into theflutter_assetsbundle at build time and does not scan undeclared files. - The bundle is read-only and lives inside the packaged app, so you read assets by key through an
AssetBundleand never by file system path. - The key is the declared path string. It is case-sensitive and relative to
pubspec.yaml. - Reads are asynchronous. Cache results instead of reloading on each build.
AssetManifestshows what was actually bundled, which makes it the first debugging tool.
Exercise
A teammate adds assets/data/levels/level1.json to the project and declares only - assets/data/ in pubspec.yaml. The app calls rootBundle.loadString('assets/data/levels/level1.json') and throws "Unable to load asset". Give the likely cause and two ways to fix it.
Show answer
A directory declaration bundles only the files directly inside that directory, not files in its subdirectories, so levels/level1.json was never bundled. Fix it by adding - assets/data/levels/ to the assets: list, or by declaring the file itself as - assets/data/levels/level1.json. After changing pubspec.yaml, restart the app instead of hot reloading.
Exercise
Why can't you open a bundled asset with File('assets/images/logo.png') from dart:io, and what should you use instead?
Show answer
The asset key is a lookup key into the app bundle, not a file system path. On Android the bundle lives inside a compressed APK, and on the web it is fetched over HTTP, so no file exists at that path. Use rootBundle.load or rootBundle.loadString, or a widget such as Image.asset, which reads through the AssetBundle.
Exercise
Which of these are Flutter assets, and which are not? (a) A JSON file listed under assets: in pubspec.yaml. (b) The Android launcher icon in android/app/src/main/res. (c) A PNG in assets/images/ that is not declared in pubspec.yaml. (d) A text file the app creates in the documents directory at runtime.
Show answer
Only (a) is a Flutter asset. (b) is a native Android resource packaged by the Android build. (c) is not bundled because Flutter only packages declared files. (d) is created after install and is writable app data, not part of the bundle.