Sub topic 2
Trimming images, assets and fonts
This chapter assumes you can edit pubspec.yaml, run flutter build, and read pubspec.lock. You should have a release build of an app you can measure.
Assets are the files your app ships with: images, JSON, fonts and icons. Every file listed under flutter: assets: in pubspec.yaml is bundled into the app, whether code uses it or not.
Trimming images and assets
Delete assets that no code references, then shrink the ones you keep. Use compressed formats such as WebP for photos and SVG for simple icons. Check each image's pixel dimensions against the size it is displayed at, because an oversized image costs bytes without adding visible detail.
Trimming fonts
Each font file is included in full. Declare only the weights you use:
flutter:
uses-material-design: true
fonts:
- family: Inter
fonts:
- asset: fonts/Inter-Regular.ttf
- asset: fonts/Inter-Bold.ttf
weight: 700Release builds tree-shake MaterialIcons by default, so unused icons are dropped automatically.
Auditing packages and their cost
A package can add native code, pull in other packages, or both. Print the dependency tree:
flutter pub deps --style=compactFor each package, ask whether it adds native code, whether it brings large transitive dependencies, and whether you use more than one function from it. Remove unused entries from pubspec.yaml, then run flutter pub get.
Obfuscation and split debug info
Obfuscation renames classes and methods, which makes the binary harder to read and slightly smaller. Split debug info moves the symbol table out of the app:
flutter build apk --obfuscate --split-debug-info=build/symbols> Keep the build/symbols folder for every release. Without it, you cannot decode stack traces from that build.
Note: the callout below uses the required fence syntax.
Deferred loading with deferred as
A Dart library imported with deferred as loads only when you await loadLibrary. Its code is not needed at startup:
import 'package:my_app/report_screen.dart' deferred as report;
Future<void> openReport() async {
await report.loadLibrary();
report.showReportScreen();
}Do not call any member of the library before loadLibrary completes.
What happens between tapping the icon and the first frame
The operating system starts a process, the Flutter engine and Dart VM start, main() runs, and runApp builds the widget tree. The first frame appears after that.
Measure these phases with:
flutter run --profile --trace-startupThis writes build/start_up_info.json. Keep main() short. Initialize only what the first screen needs before runApp, and start other work after the first frame.
Exercise
Why does deferred loading reduce startup time, and what must you do before using a deferred library?
Show answer
The deferred library's code is not loaded at startup, so the app launches with less work. Before using the library, you must await loadLibrary() so its code is available.