Sub topic 6
Auditing packages and their cost
This chapter assumes you can build a release app with flutter build apk --analyze-size and open the resulting JSON file in the DevTools app size tool. Both were covered in the earlier chapters on measuring size. You should also be comfortable editing pubspec.yaml.
Every package you add can change your download size, and the change is often not what the package's README suggests. This chapter covers what a dependency can add to a build, how to find the expensive ones, and how to decide whether to keep, replace, or defer them.
What a package can add to your build
A package's cost shows up in three places in the final binary.
| Cost | Where it appears | How to spot it |
|---|---|---|
| Compiled Dart code | The AOT snapshot (`libapp.so` on Android) | `package:<name>` nodes in the app size tree |
| Native code | `lib/<abi>/*.so` in the APK, frameworks on iOS | Extra `.so` files next to `libflutter.so` |
| Bundled assets | `assets/` and `fonts/` inside the app | Asset entries named after the package |
Dart code is tree-shaken during AOT compilation. Functions and classes that cannot be reached from main() are left out. This helps, but it has limits:
- Code reached through a barrel file or a static initializer stays in the build, even if you use only a small part of the package.
- Reflection-like patterns, large generated lookup tables, and big
constdata (such as locale or timezone databases) count in full once they are reachable. - Native libraries and assets are never tree-shaken. A plugin that ships a 3 MB
.soper ABI adds it whether or not you call the plugin.
A package that looks small on pub.dev can therefore be expensive, and a package with a large source tree can cost almost nothing.
Step 1: Map the dependency graph
Before measuring bytes, find out what you depend on. flutter pub deps prints the resolved graph:
flutter pub deps --no-dev --style=compact--no-dev leaves out dev_dependencies, which do not ship in the app. The compact style lists each package with its dependencies on one line. Use --style=tree for a nested view and --style=list for a flat one.
The graph shows transitive dependencies, which are packages you never wrote in pubspec.yaml. One direct dependency can pull in a dozen of them. The script below counts how many packages each direct dependency brings in. It uses the JSON output of flutter pub deps.
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final result = await Process.run(
'flutter',
['pub', 'deps', '--json', '--no-dev'],
runInShell: true,
);
if (result.exitCode != 0) {
stderr.writeln(result.stderr);
exit(result.exitCode);
}
final data = jsonDecode(result.stdout as String) as Map<String, dynamic>;
final packages = <String, Map<String, dynamic>>{
for (final p in data['packages'] as List)
(p as Map<String, dynamic>)['name'] as String: p,
};
Set<String> closure(String name) {
final seen = <String>{};
void visit(String n) {
if (!seen.add(n)) return;
final deps = (packages[n]?['dependencies'] as List?)?.cast<String>();
for (final d in deps ?? const <String>[]) {
visit(d);
}
}
visit(name);
seen.remove(name);
return seen;
}
final direct = packages.values
.where((p) => p['kind'] == 'direct')
.map((p) => p['name'] as String)
.toList();
final counts = {for (final name in direct) name: closure(name).length};
final sorted = counts.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
for (final e in sorted) {
print('${e.key.padRight(30)} pulls in ${e.value} packages');
}
}Run it from the project root with dart run tool/dep_counts.dart. Save the file as tool/dep_counts.dart first.
The counts include the flutter SDK package, which is large in every app, so compare the other entries against each other. A package count is a hint, not a size. A package with 20 transitive dependencies may add less than one with a single native library.
Step 2: Measure with a baseline and a diff
Package names in the graph do not tell you bytes. For bytes, use the size analysis from the previous chapters, and compare builds taken before and after a change.
- Build the current app and keep the JSON file:
``bash flutter build apk --analyze-size --target-platform android-arm64 ``
- Copy the
*-code-size-analysis_*.jsonfile frombuild/to a safe place and name it for the commit, for examplesize-before.json. Later builds can write files with similar names, and you will lose track of which is which. - Make one change: remove a package, replace it, or add the one you are considering.
- Build again with the same command and the same target platform.
- Open DevTools with
dart devtools, choose the App Size tab, and select Diff. Load the old file as the old snapshot and the new file as the new snapshot.
The diff view shows added and removed bytes in a tree. Expand package: entries to see which libraries changed. Always compare builds made with the same flags and the same Flutter version, or the diff mixes your change with unrelated ones.
Step 3: Read the tree for package cost
In the app size tool's tree view, a few places matter most for package audits:
package:nodes under the Dart AOT snapshot. The size is the compiled code the package contributes. Sort by size and look at the top 10 packages.- Native libraries. For an Android build, look at the
lib/arm64-v8a/entries. Anything other thanlibapp.soandlibflutter.socame from a plugin or a native SDK it wraps. - Assets. Packages can declare their own assets and fonts. Entries under
assets/packages/<name>/or font files belong to that package.
A typical finding is that a single package accounts for a surprising share of the Dart code. Common causes are a full-featured date or localization library loaded for one format string, an SDK client generated from a huge API schema, or a charting library used for one small graph.
Step 4: Decide what to do with an expensive package
Once you know a package is costly, there are five realistic options. Choose in this order, because the earlier options are cheaper to carry out.
- Remove it. Check whether the feature is still used. Dead dependencies are common after a redesign. Use
flutter pub remove <name>and let the analyzer show what breaks. - Replace it with a smaller or lighter package. Compare candidates by measuring, not by reading the pub.dev page. Replacing a large package is only worthwhile if the new one covers the features you use.
- Replace it with a few lines of your own code. This suits packages that you use for one function, such as a string helper or a simple color utility. Keep it for cases where the code is easy to test and unlikely to change.
- Defer it. If the package is used on a rarely visited screen, load it with
deferred as, covered in a later chapter in this series. Deferring does not remove the code from the download on iOS or in a plain APK, but it keeps it off the startup path. On Android app bundles it can also be delivered separately. - Keep it, and record why. Some packages are worth their size. Write down the cost in your pull request or in a short note so the next person does not repeat the audit.
Common errors in package audits
- Judging by package count. A package with no dependencies can still ship a large asset or native library. Measure bytes.
- Auditing a debug build. Debug builds include the JIT runtime and unoptimized code, so the package sizes are meaningless. Always use release builds.
- Forgetting dev dependencies.
dev_dependenciesdo not ship, so removing them does not shrink the app. They do affect build time, which is a separate concern. - Changing several things at once. If you remove two packages and upgrade Flutter in one step, the diff cannot tell you which change helped.
- Ignoring other platforms. A plugin may add a large native framework only on iOS or only on Android. Check each platform you ship, not just the one you develop on.
- Skipping version updates. Newer versions of a package sometimes drop heavy transitive dependencies. Run
flutter pub outdatedto see which packages have newer versions, and measure again after upgrading.
A short worked example
Suppose the audit script reports that fancy_charts pulls in 18 packages, and the diff after removing it shows 1.4 MB less in the arm64-v8a APK. A search of the project shows it is used on a single statistics screen to draw one line graph.
You have two reasonable choices. You can replace it with a small custom painter, which costs a few hours of work and removes the package entirely. Or you can defer the statistics screen, which costs a few lines of code and keeps the 1.4 MB off the startup path but not off the download. Which you pick depends on whether you are trying to cut download size or startup time. In either case, record the measured number, and the next audit will start from a known baseline.
Exercise
You remove a package from pubspec.yaml and rebuild with flutter build apk --analyze-size. The new total is about 200 KB larger than before. Name two likely reasons that do not involve the removed package.
Show answer
The two builds were probably not comparable. Likely causes include a different Flutter SDK version, a different target platform or build flags, or a build made in a different mode. A transitive dependency may also have resolved to a newer version when pubspec.lock changed. Rebuild both from the same commit, SDK and flags before comparing.
Exercise
A plugin adds only 40 KB to the package: nodes of the Dart snapshot, but your APK grew by 2 MB after adding it. Where should you look, and why can tree shaking not help?
Show answer
Look at the native libraries (the .so files under lib/<abi>/) and at the assets declared by the package. Tree shaking applies only to Dart code during AOT compilation. Native libraries and assets are copied into the app whole, so they stay in the build even if you call only one function of the plugin.
Exercise
Why does the audit workflow insist on changing one package at a time and keeping the JSON file from each build?
Show answer
The diff view compares two JSON files, and it can only attribute a size change to a cause if exactly one thing differs between them. Keeping each file lets you compare any two builds later, and changing one package at a time makes the cause of each change clear.