Sub topic 10
Keeping Bundled Assets from Bloating the App
This chapter assumes you can declare assets and fonts in pubspec.yaml, load them with Image.asset and rootBundle, and build a release app from the command line. It also assumes you know the 2.0x/3.0x variant layout from earlier chapters. Here the question is what those declarations cost, how to measure the cost, and how to reduce it.
Why assets dominate download size
Compiled Dart code for a typical app is a few megabytes. A set of unoptimized photos, a few font families, and a bundled video can easily exceed that. Assets are often the largest part of an app you can control.
When you build a release app, Flutter copies every declared asset into a flutter_assets directory inside the package. On Android this is assets/flutter_assets/ inside the APK or AAB. On iOS it sits inside the app bundle's Frameworks/App.framework. The files are copied as they are, along with a generated asset manifest. Flutter does not resize, re-encode, or deduplicate your images.
This has three consequences:
- Every declared file ships to every user, whether or not any screen uses it.
- Resolution variants are not split per device. The Android density splits that Play applies to native resources do not apply to Flutter assets, so a phone that only needs
2.0x/logo.pngstill receives the1.0xand3.0xfiles. - Size grows with what you declare, not with what you load. An asset that no code ever references still costs bytes.
Assets also cost memory when decoded, which is a different problem. A 4000×3000 JPEG may be 1.5 MB on disk but decodes to about 48 MB of pixels (width × height × 4 bytes). This chapter is about install and download size. Decode memory is covered in the callout below.
Measuring before changing anything
Guessing which asset is heavy wastes time. Flutter can break down a release build for you.
flutter build apk --analyze-size --target-platform android-arm64The command prints a tree of the compressed size by category. Look at the entries under assets/flutter_assets, which list your images, fonts, and data files. It also writes a *-code-size-analysis_*.json file under ~/.flutter-devtools/, and the output includes the exact path. You can load that file in the DevTools app size tool, or compare two builds:
dart devtools --appSizeBase=old-analysis.json --appSizeTest=new-analysis.jsonThe same flag works for flutter build appbundle, flutter build ios, and the desktop targets. Always analyze a release build. Debug and profile builds are not representative, and --analyze-size is only supported for release.
For a quick look without DevTools, list the largest files in the archive:
unzip -l build/app/outputs/flutter-apk/app-release.apk \
| grep flutter_assets \
| sort -k1 -n -r \
| head -20The first column is the uncompressed size in bytes, so the biggest files appear first. This shows uncompressed sizes, so use --analyze-size for the compressed figures that match the download.
Declare only what you ship
The most common source of waste is the directory declaration. Declaring assets/images/ includes every file directly inside that folder, plus the resolution-variant folders that sit beside those files. It does not include other subfolders. Developers often respond by dumping everything into one folder, including files that were never meant to ship: design sources, unused experiments, and screenshots.
Keep two rules:
- Store source art outside any declared directory. A
design/folder at the project root, never listed inpubspec.yaml, can hold.psd,.sketch,.fig, and full-resolution originals. - Prefer narrow declarations for large or rarely used groups. Declare a directory when everything in it is meant to ship. Declare single files when only a few are used.
flutter:
assets:
- assets/images/icons/
- assets/images/onboarding/welcome.webp
- assets/data/config.jsonSubfolders are not recursive. If assets/images/icons/ has a subfolder social/, add assets/images/icons/social/ as its own line. This is also a size feature: a forgotten subfolder is a missing asset at runtime, but a folder you never listed costs nothing.
Removing unused assets
Flutter does not warn about declared but unreferenced assets. A simple audit uses grep on filenames:
for f in assets/images/*; do
name=$(basename "$f")
if ! grep -rq "$name" lib/; then
echo "unreferenced: $f"
fi
doneThis finds only literal references. Assets built from dynamic strings, such as 'assets/images/level_$n.png', will show up as false positives. Review the list by hand before deleting anything, and keep the files in version control so you can restore them.
Choosing formats and dimensions
Image content is usually the biggest lever. Compare the options for the kind of image you have:
| Content | Better choice | Why |
|---|---|---|
| Photographs | WebP or JPEG at moderate quality | Lossy compression is designed for photographic detail |
| Flat UI art with transparency | Lossless WebP, or optimized PNG | Keeps sharp edges and the alpha channel at a smaller size than raw PNG |
| Simple icons and logos | Vector (SVG via a package such as `flutter_svg`, or an icon font) | One small file for every density |
| Large backgrounds | Lower-resolution file, or download at runtime | A full-screen image rarely needs more than the screen's pixel size |
Flutter's image decoder supports WebP, JPEG, PNG, GIF, and BMP on all platforms. Re-encoding a 2 MB PNG photograph to WebP at quality 80 often cuts it to a fraction of its size with no visible change. Command-line tools such as cwebp (from Google's libwebp) do this:
cwebp -q 80 hero.png -o hero.webpAlready-compressed formats such as JPEG and WebP gain almost nothing from the package archive's own compression, so shrink them at the source.
Do you need all three densities?
The 2.0x and 3.0x variants multiply the image bytes on disk. A 3.0x variant is nine times the pixels of the 1.0x file. Trade-offs:
- Shipping only the base file works. Flutter scales it to the device pixel ratio, but on high-density screens it looks soft.
- Shipping only a high-resolution base file is sharp, and Flutter downscales it. This ships one large file instead of three, and decoding costs more memory unless you set
cacheWidth. - Photos and backgrounds are often best as one well-sized file. Small icons and thin lines show the difference on dense screens, so keep their variants or switch them to vectors.
There is no universal answer. Measure with --analyze-size, then check the result on a real high-density device.
Fonts
A single TrueType font file can run from about 50 KB for a Latin-only face to several megabytes for a family that includes CJK (Chinese, Japanese, Korean) glyphs. A family with regular, bold, italic, and bold italic files can add up quickly.
Declare only the faces you use
Every asset: entry under a font family ships. If the app never uses italics, drop the italic entry:
flutter:
fonts:
- family: Raleway
fonts:
- asset: assets/fonts/Raleway-Regular.ttf
- asset: assets/fonts/Raleway-Bold.ttf
weight: 700If code later asks for FontStyle.italic with this declaration, Flutter does not fail. It synthesizes a slanted version of the regular face, which looks worse than a real italic. Decide on that trade-off deliberately.
Subset large fonts
If you use a large font for a small set of characters, such as a display font for headings, you can create a subset that contains only the glyphs you need. The fonttools Python package provides pyftsubset:
pip install fonttools brotli
pyftsubset Raleway-Regular.ttf \
--unicodes="U+0020-007E,U+00A0-00FF" \
--output-file=Raleway-Regular-latin.ttfThis keeps basic Latin and Latin-1 punctuation. Check the license of the font first, because some licenses restrict modification, and test every language your app supports. A missing glyph shows as an empty box.
Variable fonts
A variable font stores a range of weights in one file. Flutter supports them through FontVariation in TextStyle.fontVariations. One variable file can replace four static files, but a variable file is larger than any single static one, and the benefit depends on the font. Compare real sizes before switching.
Icon fonts are shrunk for you
For icon fonts such as MaterialIcons, the release build performs icon tree shaking. It scans your compiled code for the IconData constants you use and writes a font containing only those glyphs. The saving is large, since the full Material icon font is over a megabyte.
Tree shaking only works if icons are referenced as constants:
import 'package:flutter/material.dart';
// Tree-shakeable: the code point is a compile-time constant.
const Icon home = Icon(Icons.home);
// Breaks tree shaking: the code point is computed at runtime.
Icon fromCode(int code) => Icon(IconData(code, fontFamily: 'MaterialIcons'));When the tool cannot prove all icon lookups are constant, the build fails with a message that mentions --no-tree-shake-icons. The better fix is to make the icon constant. The flag disables the saving for every icon font in the build, so use it only as a last resort.
Assets from packages
When your app depends on a package that declares assets or fonts in its own pubspec.yaml, those files are bundled into your app under packages/<package_name>/. You cannot choose to leave them out. If a dependency ships a 5 MB font family for one optional feature, your app carries it.
Look at the analysis output for entries beginning with packages/. If one package contributes a lot of data, consider an alternative package, a fork with trimmed assets, or removing the dependency. Your own declared assets in pubspec.yaml are never copied into other packages' bundles, so duplication happens only when you copy a package's file into your own folder.
Keeping large assets out of the bundle
Some assets are too big to ship at all: videos, offline map tiles, ML models, and large level packs. Three approaches work.
Download and cache at runtime
The app ships without the file, downloads it on first use, and stores it in the application documents directory. This sketch uses the http and path_provider packages:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
Future<File> fetchCached(String url, String fileName) async {
final dir = await getApplicationSupportDirectory();
final file = File('${dir.path}/$fileName');
if (await file.exists()) {
return file;
}
final response = await http.get(Uri.parse(url));
if (response.statusCode != 200) {
throw HttpException('Download failed: ${response.statusCode}', uri: Uri.parse(url));
}
await file.writeAsBytes(response.bodyBytes);
return file;
}You then display the result with Image.file, not Image.asset. The cost is that the feature needs a network on first use. Plan for loading and error states, and for the user clearing app data.
Asset flavors
If different build flavors need different assets, such as a free and a paid edition, restrict assets to flavors so each build contains only its own. Flutter supports this on asset entries from version 3.19:
flutter:
assets:
- assets/common/
- path: assets/free/
flavors:
- free
- path: assets/pro/
flavors:
- proAn entry with no flavors key is included in every build. Build with flutter build apk --flavor free and the assets/pro/ folder stays out.
Deferred components on Android
Android deferred components let you move Dart libraries and assets into modules that Google Play delivers on demand. They are declared under deferred-components: in pubspec.yaml and require app bundle builds and Play delivery. They do not exist on iOS or the web, so treat them as an Android-only optimization with extra setup.
A decision path
Common mistakes
- Analyzing a debug build. The numbers are unrelated to what users download. Use
--analyze-sizeon a release build. - Declaring the project's
assets/root. This sweeps in every file directly inside it. Declare specific folders. - Committing design sources into a declared folder. Move them to a folder that is never listed.
- Using
--no-tree-shake-iconsto silence a build error. Fix the non-constantIconDatainstead. - Assuming the app bundle (AAB) will remove unused density variants. It does not for Flutter assets.
- Optimizing without a baseline. Save the analysis JSON before changes so you can compare afterwards.
A short workflow
- Run a release
--analyze-sizebuild and keep the JSON as a baseline. - Identify the three largest items under
flutter_assetsand underpackages/. - Fix the largest first: re-encode, resize, drop, or move out of the bundle.
- Rebuild and compare with
--appSizeBaseand--appSizeTest. - Test on a real device, including a high-density screen, to confirm the images and fonts still look right.
Exercise
Your pubspec.yaml lists assets/images/. The folder contains hero.png, a 2.0x/hero.png, a 3.0x/hero.png, and a subfolder old/ with 40 unused PNG files. Which of these files end up in the release build, and how would you stop shipping the ones you do not need?
Show answer
hero.png and its 2.0x and 3.0x variants are bundled. The files in old/ are not bundled, because directory declarations are not recursive and old/ was never listed. If you later add assets/images/old/ to pubspec.yaml, all 40 files ship, so keep unused files out of declared folders or delete them. To stop shipping the 2.0x and 3.0x variants, delete those files, and expect softer images on high-density screens unless the base file is large.
Exercise
A release build fails with an error about non-constant IconData and suggests --no-tree-shake-icons. Why does the error occur, what does the flag cost you, and what is the better fix?
Show answer
Icon tree shaking keeps only the glyphs whose code points the compiler can find as constants. Creating IconData from a runtime value, such as an integer from a server, prevents that analysis, so the build stops. The flag disables tree shaking for every icon font and puts the whole font, often over a megabyte, back in the app. The better fix is to use constant IconData values, for example a map from server keys to Icons.* constants, so the shaker can still trim the font.
Exercise
Your app has a 25 MB intro video declared as an asset. Name two ways to remove it from the install bundle and one drawback of each.
Show answer
Download it at runtime and cache it in the app's support directory. The drawback is that the first playback needs a network and you must handle download errors. Alternatively, move it into an Android deferred component delivered by Google Play. The drawback is that it works only on Android, needs app bundle builds, and adds setup and loading logic. Asset flavors are a third option only if the video belongs to one flavor.