Sub topic 8
Deferred loading with deferred as
This chapter assumes you can edit pubspec.yaml, use async/await and Future in Dart, and build a release app with the flutter tool. It also assumes you have already measured your app with --analyze-size, as covered earlier in this tutorial. Deferred loading is a tool for code that you have measured and found to be large.
What a deferred import does
A normal Dart import makes a library available as soon as the program starts. A deferred import postpones that until your code asks for it.
import 'package:my_app/report_screen.dart' deferred as report;The deferred as report part has three effects:
- The library is not loaded when the app starts.
- Its members are reachable only through the
reportprefix, and only after loading. - The prefix gains a
loadLibrary()method that returns aFuture<void>. The future completes once the library is ready.
The library is a normal Dart file. Nothing in it marks it as deferred. Only the import does.
import 'package:flutter/material.dart';
class ReportScreen extends StatelessWidget {
const ReportScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Report')),
body: const Center(child: Text('Quarterly report')),
);
}
}Rules the compiler enforces
Because the library may not be loaded yet, Dart restricts how you use it:
- You cannot use the library's types in the importing file. That means no type annotations,
extends,implementsoronclauses that name them. Use a type from a non-deferred library instead, such asWidget. - You cannot use its constants as compile-time constants in the importing file. A
constexpression cannot refer to anything in a deferred library. - You can call its functions and constructors through the prefix, but only after
loadLibrary()has completed. Before that, the call fails at run time. In a release build, this is a real error you will see in testing. - Its top-level initializers do not run at app start. They run when the library loads.
Rule 1 matters in practice. If you want a variable holding a ReportScreen, declare it as Widget.
Loading is a Future
loadLibrary() can be called many times. The first call does the work, and later calls return a future that completes immediately with the already loaded library. You do not need your own "already loaded" flag. You do need to avoid creating a new future on every build, because that restarts your FutureBuilder each time the widget rebuilds.
This is a complete app that defers a second screen:
import 'package:flutter/material.dart';
import 'package:my_app/report_screen.dart' deferred as report;
void main() => runApp(const MaterialApp(home: HomeScreen()));
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const DeferredReport()),
);
},
child: const Text('Open report'),
),
),
);
}
}
class DeferredReport extends StatefulWidget {
const DeferredReport({super.key});
@override
State<DeferredReport> createState() => _DeferredReportState();
}
class _DeferredReportState extends State<DeferredReport> {
late Future<void> _loading = report.loadLibrary();
void _retry() {
setState(() {
_loading = report.loadLibrary();
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder<void>(
future: _loading,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Could not load this screen.'),
TextButton(onPressed: _retry, child: const Text('Retry')),
],
),
),
);
}
if (snapshot.connectionState != ConnectionState.done) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return report.ReportScreen();
},
);
}
}The report.ReportScreen() call is allowed because the app only reaches it after the future has completed. The builder returns a Widget, so no deferred type appears in a declaration.
The error branch matters for real deferred downloads, covered below. Loading can fail when a device is offline or low on storage. A screen that spins forever is worse than one that offers a retry.
What actually gets deferred
The Dart language feature is the same everywhere. The size benefit depends on the platform.
| Target | What deferral does |
|---|---|
| Web | The compiler splits the deferred library into a separate JavaScript file. The browser downloads it on `loadLibrary()`. The initial download shrinks. |
| Android with deferred components | The release build puts the library in a separate loading unit. Google Play delivers it on demand. The initial download shrinks. |
| Android without deferred components | The code stays in the base install. `loadLibrary()` still works, but the download does not shrink. |
| iOS and desktop | The code ships in the app binary. Deferral gives no download savings. |
So there are two separate benefits: a smaller download, and a shorter load path at startup. Only some targets give you the first. The second depends on how the library is loaded. Treat any claim about startup gains as something to check with --trace-startup, not something to assume.
In debug mode, the code is compiled just in time and is all present, so loadLibrary() completes almost immediately. Do not judge deferred loading by how it behaves under flutter run in debug mode. Test it in a release or profile build.
Android deferred components
To get a smaller Android download, you declare which libraries go into separate components. You add an entry to the flutter section of pubspec.yaml:
flutter:
deferred-components:
- name: reportComponent
libraries:
- package:my_app/report_screen.dartYou then build an app bundle, because Play Feature Delivery needs .aab files:
flutter build appbundle --releaseOn the first builds, the Flutter tool validates your Android project. It reports which files are missing, such as the component's Gradle module and string resources, and it writes a file describing the loading units it found. You apply those changes, rebuild, and repeat until validation passes. Read the official "deferred components" page for your Flutter version, since the required Android setup files have changed over time.
Some limits to plan for:
- Deferred components work only in release builds of app bundles. APKs built with
--split-per-abihave no on-demand delivery. - The first call to
loadLibrary()may need a network download. It is not a cheap local operation, so design for a visible loading state. - Assets can also be assigned to a deferred component in
pubspec.yaml. That helps if the deferred feature has large images.
Choosing what to defer
Good candidates are large and used by few people on a given run:
- An admin or settings area that few users open.
- A heavy feature, such as a PDF viewer, a map screen or a video editor.
- A rarely used screen that pulls in a large package.
Poor candidates:
- Anything on the first screen, since you would need it at once.
- Small libraries, because the cost of the extra loading step and its error handling outweighs a few kilobytes.
- Code the user is very likely to open in their first few seconds. They will see a spinner where they once saw a screen.
Use the DevTools app size tool to decide. Find the package or library with a large share of the Dart AOT snapshot. Check whether the tool shows it in a screen that only some users reach. Then defer that screen's entry library.
Why your deferral may have no effect
The most common failure is that the code is still imported normally somewhere else. A library is deferred only if every path that reaches it is deferred. Suppose report_screen.dart is deferred in home.dart, but settings.dart imports it normally. The compiler then keeps it in the main part of the app, and the size analysis shows no change.
You can look for this problem:
- Search the project for the library's file name with
grep -rn "report_screen.dart" lib. - Check that each result uses
deferred as. - Check the transitive imports. A shared package your deferred library uses may also be used by the main app. That shared code stays in the main part, and only the code unique to the deferred library moves out.
- Rebuild with
--analyze-sizeand compare to your earlier result.
The last point is a limit of the technique. If the heavy code is a package used on the home screen too, deferring the second screen does not remove it.
A load sequence
Preloading to hide the wait
If you know the user will probably need the feature, start loading before they ask. You can trigger the load at an idle moment, for example after the first frame:
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:my_app/report_screen.dart' deferred as report;
void preloadReport() {
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(report.loadLibrary().catchError((Object e) {
debugPrint('Preload failed, will retry on demand: $e');
}));
});
}A failed preload is harmless, because the on-demand call that happens later tries again. This pattern gives back the instant feel while keeping the code out of the initial download. Do not use it for everything. Preloading every deferred library at startup moves the same work back onto the startup path, which defeats the point.
Common errors
- Using a deferred type in a declaration. The analyzer reports an error. Use
Widgetor another non-deferred type. - Calling members before the load completes. Always
awaitthe future, or gate the call behind aFutureBuilder. - Recreating the future in
build. Store it in state, as in the example. - Testing only in debug mode. You will miss both the loading delay and the failure paths.
- Expecting savings on iOS. The code is in the binary, so the download size is unchanged.
Exercise
Your app's home screen imports package:my_app/charts.dart normally. A settings screen, reached by few users, also uses it. A colleague changes only the settings screen to import 'package:my_app/charts.dart' deferred as charts; and finds that the release size did not change. Why, and what must change?
Show answer
The home screen still imports the library normally, so the compiler must keep it in the main part of the app. A library is deferred only if every import of it is deferred. To get a saving, either make the home screen's import deferred too (only if it can tolerate waiting for the load), or accept that the code is part of the main app and instead defer something that only deferred screens use. Then rebuild with --analyze-size and compare.
Exercise
A screen builds FutureBuilder(future: report.loadLibrary(), ...) directly inside build. Name one problem and give the fix.
Show answer
Each rebuild creates a new call, so the builder restarts and can flash a spinner. The call also hides any error state from the widget's lifecycle. Store the future in a State field, for example late Future<void> _loading = report.loadLibrary();, and pass that field to the builder. Add a retry that assigns a new future with setState.