Sub topic 5
Trimming images, assets and fonts
Assets are often the largest part of a Flutter app that you control directly. The engine and compiled Dart code are mostly fixed costs. Images, bundled data files and fonts are your choices, and you can change them without touching application logic.
This chapter assumes you can edit pubspec.yaml, you have run flutter build in release mode, and you know how to read the --analyze-size output from the previous chapter. The examples target a typical mobile app, with notes where web or desktop differ.
How assets end up in the build
Everything listed under flutter: assets: in pubspec.yaml is copied into the app package. A directory entry such as assets/images/ includes every file directly inside that directory, but not files in its subdirectories. Large files you forgot about, such as a 6 MB design export or an unused video, ship with the app.
The package then compresses most of these files. That helps for text formats such as JSON. It does little for formats that are already compressed, such as PNG, JPEG, WebP and MP3. Download size follows file size closely for those.
You can see the contribution of assets in two places:
- The
--analyze-sizetree in DevTools, where asset entries appear under theflutter_assetsbranch. - The Android Studio APK Analyzer, or
unzip -l app-release.apk, which lists each file with its compressed size.
flutter build apk --analyze-size --target-platform android-arm64
unzip -l build/app/outputs/flutter-apk/app-release.apk | sort -k1 -n -r | head -20The second command sorts by uncompressed size, largest first, so the biggest offenders appear at the top.
Images
Ship the pixels you display
The most common waste is an image far larger than any screen needs. A 4000 by 3000 pixel photo shown in a 360 dp wide card carries about 100 times more pixels than a phone can show. Resize source images to the largest size at which they are actually drawn, which is the layout size in dp multiplied by the highest device pixel ratio you target. A ratio of 3.0 covers most phones.
Choose the format
| Content | Good choice | Notes |
|---|---|---|
| Photographs | WebP (lossy) or JPEG | Lossy WebP is usually noticeably smaller than JPEG at similar quality. |
| Screenshots, UI art with transparency | WebP (lossless) or optimized PNG | Run PNGs through an optimizer such as `oxipng` or `pngquant`. |
| Simple logos and illustrations | Vector via a package such as `flutter_svg` | Costs a package and a parse at load time, but scales without extra files. |
| Animated content | Lottie JSON or a short video | Animated GIFs are very large for what they show. |
Flutter decodes WebP on all supported platforms. Check the Flutter documentation for current format support before using less common formats such as AVIF.
Use resolution-aware variants carefully
Flutter picks among variants stored in 1.0x, 2.0x and 3.0x style directories. You declare only the main asset directory, and the framework finds the variants.
assets/images/logo.png (1.0x)
assets/images/2.0x/logo.png
assets/images/3.0x/logo.pngThis is a trade-off. Each variant is a separate file in your package, so three variants triple the cost of that image. For large photographs, the lower-density variants save memory at runtime but add to the download. Often one well-chosen file is the better choice. Keep variants for small UI graphics, where sharpness matters and the extra bytes are tiny.
Cache size is not bundle size
Image.asset accepts cacheWidth and cacheHeight. These make the engine decode the image at a smaller size, which reduces memory use and decode time. They do not shrink the file in your package. Use them when you cannot resize the source, and do not count them as a size fix.
import 'package:flutter/material.dart';
void main() => runApp(const GalleryApp());
class GalleryApp extends StatelessWidget {
const GalleryApp({super.key});
@override
Widget build(BuildContext context) {
// cacheWidth is in physical pixels, so scale the layout width.
final pixelRatio = MediaQuery.devicePixelRatioOf(context);
final cacheWidth = (360 * pixelRatio).round();
return MaterialApp(
home: Scaffold(
body: Image.asset(
'assets/images/hero.webp',
width: 360,
cacheWidth: cacheWidth,
fit: BoxFit.cover,
),
),
);
}
}The snippet needs assets/images/hero.webp declared in pubspec.yaml.
Other assets
Review every non-image file under your asset directories.
- JSON and text data: minify them, and remove fields the app never reads. Large static datasets are better served from a backend or a CDN and cached after first use.
- Audio and video: use compressed formats with a bitrate suited to the content. Speech does not need music bitrates.
- Leftover files: design source files (
.psd,.sketch,.fig) and unused exports often sit in asset folders. Move them outside the declared directories. - Per-variant assets: if you build flavors, such as a free and a paid edition, the
flavorskey on an asset entry restricts a file to the listed flavors.
flutter:
assets:
- assets/images/
- path: assets/premium/theme_pack.webp
flavors:
- paidEntries that use path: can also have a transformers: list, which runs a Dart command-line tool over the file at build time. This is how you can automate steps such as compression for specific files, but check your Flutter version's documentation for the supported syntax before relying on it.
To find unused assets, search your code for each file name. A simple approach is a script that lists files in assets/ and runs grep -r for each name in lib/. It will miss assets whose paths are built from string interpolation, so review the results by hand.
Fonts
Icon fonts are tree-shaken for you
In release builds, Flutter shrinks icon fonts such as MaterialIcons and CupertinoIcons to only the glyphs your code references. This can reduce a font of over a megabyte to a few kilobytes. The build prints the saving, for example "Font asset MaterialIcons-Regular.otf was tree-shaken".
Tree shaking works only when the compiler can see which icons you use. A non-constant IconData, such as one created from a runtime code point (IconData(codePoint, fontFamily: 'MaterialIcons')), makes the build fail with a message that it cannot tree shake icon fonts. The usual fix is to use constant icons. The escape hatch is --no-tree-shake-icons, which keeps the full font and removes the saving.
flutter build apk --release
flutter build apk --release --no-tree-shake-iconsCompare the two sizes once to see how much the shaking saves in your app.
Custom text fonts
Text fonts are not tree-shaken. Every file you declare is bundled whole. A family with eight weights and italics can add several megabytes. Reduce it in this order:
- Declare only the styles you use. If the design uses regular and bold, drop the other six files from
pubspec.yamland from the repository. - Prefer a variable font when you need many weights. One variable file can replace several static ones, though it is larger than a single static weight. Compare actual sizes.
- Subset the glyphs. If your app only needs Latin characters, remove the Cyrillic, Greek and CJK ranges. The
pyftsubsettool from thefonttoolsPython package does this.
pip install fonttools
pyftsubset assets/fonts/Inter-Regular.ttf \
--unicodes="U+0020-007E,U+00A0-00FF" \
--layout-features='*' \
--output-file=assets/fonts/Inter-Regular-subset.ttfThen point the font declaration at the subset file:
flutter:
fonts:
- family: Inter
fonts:
- asset: assets/fonts/Inter-Regular-subset.ttf
- asset: assets/fonts/Inter-Bold-subset.ttf
weight: 700The `google_fonts` package
By default, google_fonts downloads font files at runtime and caches them. That keeps them out of your package, but the first use needs network access and can cause a visible font swap. If you bundle the font files in assets/google_fonts/ instead, they count toward your package size, and you can disable runtime fetching. Decide per app: a smaller download with a network dependency, or a larger one that works offline from the first launch.
Measure the effect
Change one thing at a time and rebuild with the same command and target platform. Record the compressed download size and the flutter_assets portion from the size report. Savings from assets apply to every ABI, so they show up in each split APK as well as in the bundle.
Exercise
Your size report shows a 2.4 MB NotoSans family with eight static weight files, but the design uses only regular and bold, and the app is English only. List three steps to reduce this cost, and say which one risks breaking text.
Show answer
First, remove the six unused weight files from pubspec.yaml and from the repository. Second, subset the two remaining files to Latin ranges with pyftsubset. Third, rebuild and compare the --analyze-size result. Subsetting is the step that risks breaking text, because characters outside the kept ranges render as missing-glyph boxes. That matters if the app later adds translations or accepts user-typed text in other scripts.
Exercise
A teammate adds cacheWidth: 300 to a large Image.asset and reports that the app got smaller. Is that correct? What does the change affect?
Show answer
No. cacheWidth makes the engine decode the image at a smaller size, so it lowers memory use and decode time. The image file in the package is unchanged, so the download size stays the same. To shrink the package, resize or recompress the source file.