Sub topic 9
What happens between tapping the icon and the first frame
This chapter assumes you can run a Flutter app from the command line, know the difference between debug, profile and release builds, and are comfortable with async/await. It describes the stages a launch goes through. The next chapter shows how to measure them with --trace-startup.
Why the phases matter
"Startup time" is not one number. It is a sequence of stages, and different people own different stages. The operating system owns some of them. The Flutter engine owns others. Your Dart code owns the rest. A slow launch can only be fixed once you know which stage is slow. Rewriting main() does nothing if the time goes to loading the engine.
This chapter splits the launch into stages, says which ones you control, and explains why the way you write main() and the first build determines when the user sees something.
Cold, warm and hot starts
Platforms describe three kinds of launch. Only one is the hard case.
| Start type | State when the user taps the icon | Cost |
|---|---|---|
| Cold | The app process does not exist. | Highest. Every phase below runs. |
| Warm | The process may exist, but the Activity or view controller must be recreated. | Medium. Some phases are skipped. |
| Hot | The app is in the background and only comes to the foreground. | Lowest. Your Dart code usually does not restart. |
Measure cold starts. A cold start is what a new user sees after installing, after a reboot, or after the OS has evicted the process. It is also the only start where your own main() runs.
The stages of a cold start
The names differ between Android and iOS, but the order is the same.
1. Process creation and launch screen
When the user taps the icon, the operating system creates the process and maps the executable. On Android the system forks the process from a template process and shows a window using your launch theme. On iOS the system loads the executable and shows the launch storyboard.
You influence this stage only indirectly. A larger binary and more native libraries mean more to map and load. This is one reason the size work in earlier chapters also helps startup.
2. Native app code
Android runs your Application class and creates the FlutterActivity. iOS runs the AppDelegate and creates a FlutterViewController. Native plugins register themselves here.
Flutter plugin registration is normally generated code and is cheap. Native SDKs you start in this stage are not. If you added an analytics or crash SDK that initializes in Application.onCreate or didFinishLaunching, its cost lands before Flutter has started.
3. Engine load and initialization
The Flutter engine is a native library (libflutter.so on Android, Flutter.framework on iOS). It must be loaded and initialized. The engine locates the compiled Dart code and the asset bundle, and creates the threads it uses for the UI, the raster work and I/O.
In a release build the Dart code is ahead-of-time (AOT) compiled, so there is no compile step at launch. A debug build instead uses a just-in-time (JIT) setup and loads a much larger kernel file, which is why debug startup is slow and tells you little about production. Chapter one covered this.
4. Dart VM and main isolate
The engine starts the Dart VM and creates the main isolate. An isolate is Dart's unit of concurrency: its own memory heap and event loop, with no shared memory. Your UI code runs on this main isolate, which this chapter calls the UI isolate. The VM loads the compiled snapshot into it and prepares to call your entry point.
5. main() and runApp
Now your code runs. The Dart entry point main() is called. Everything before runApp delays the first frame, because the framework has nothing to draw until you give it a root widget.
This is the first stage you fully control.
6. The first frame
After runApp the framework attaches the root widget and schedules a frame. The frame has two halves:
- UI work (build, layout, paint): runs on the UI isolate. It turns widgets into a render tree and records drawing commands.
- Raster work: runs on a separate raster thread. It converts the commands into pixels using the GPU.
The first frame is only done when both halves finish. The launch screen disappears only after this point, so the user never sees a blank window if the launch screen is configured well. Chapter 13 covers that.
Where startup time hides in your code
Four patterns account for most avoidable delay in stage 5 and the start of stage 6.
- Awaiting before
runApp. Eachawaitinmain()beforerunApppostpones the first frame by the duration of that call. Common culprits are opening a database, reading preferences, initializing analytics and fetching remote configuration. - Heavy synchronous work. A loop that parses a large JSON file blocks the UI isolate. No frame can be produced until it finishes, even though nothing is awaited.
- An expensive first screen. A first
buildthat creates hundreds of widgets, decodes large images, or starts several network requests takes longer to render. - Deferred first frame. Calling
WidgetsBinding.instance.deferFirstFrame()tells the framework not to render until you callallowFirstFrame(). This is legitimate for waiting on a required resource, but forgetting to callallowFirstFrame()leaves the app on its launch screen forever.
Here is a main() that exhibits the first pattern.
import 'package:flutter/widgets.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await openDatabase();
await loadRemoteConfig();
await initAnalytics();
runApp(const MyApp());
}
Future<void> openDatabase() async {
await Future<void>.delayed(const Duration(milliseconds: 150));
}
Future<void> loadRemoteConfig() async {
await Future<void>.delayed(const Duration(milliseconds: 400));
}
Future<void> initAnalytics() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Center(child: Text('Hello')),
);
}
}The delays stand in for real work. The three calls run one after another, so the first frame waits about 650 ms. If only the database is needed to draw the first screen, the other two calls do not belong here.
Observing the stages yourself
A Stopwatch started on the first line of main() shows the gap between your code starting and the first frame being scheduled. It does not include stages 1 to 4.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
void main() {
final Stopwatch sinceMain = Stopwatch()..start();
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
WidgetsBinding.instance.addPostFrameCallback((_) {
debugPrint('First frame built ${sinceMain.elapsedMilliseconds} ms after main()');
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Center(child: Text('Hello')),
);
}
}The callback registered with addPostFrameCallback runs after the first frame is built and laid out. It fires on the UI isolate, so it does not tell you when the raster thread finished. For the full picture from process start to rasterized frame you need the tool described in the next chapter.
Which stages you can change
| Stage | Can you change it? | Main levers |
|---|---|---|
| 1. Process creation | Indirectly | Smaller binary, fewer native libraries |
| 2. Native app code | Yes | Delay native SDK initialization, keep `Application` and `AppDelegate` light |
| 3. Engine load | Mostly no | Use a current Flutter version, keep the app small |
| 4. Dart VM and isolate | Mostly no | Smaller snapshot through less code and deferred libraries |
| 5. `main()` | Yes | Fewer awaits, less work before `runApp` |
| 6. First frame | Yes | Simpler first screen, fewer images and requests |
Stages 5 and 6 give the largest gains for the least effort, which is why chapter 11 focuses on them.
Common mistakes
- Measuring in debug mode. The numbers are large and misleading.
- Measuring on an emulator or a fast phone only. Startup cost grows on low-end hardware. Test on the slowest device your users have.
- Assuming
runAppshows something instantly. The first frame still needs build, layout, paint and raster, and the first screen can take real time. - Moving work after
runAppand then blocking the UI isolate. Work scheduled after the first frame still competes with later frames. Chapter 12 shows how to move CPU-heavy work to another isolate. - Confusing cold and warm starts. Quitting an app from the task switcher usually produces a cold start. Backgrounding it usually does not.
Exercise
A teammate adds await Firebase.initializeApp() and await prefs.getInstance() at the top of main(), before runApp. Startup gets 300 ms slower. In which stage of the cold start does that delay occur, and why does it delay the first frame?
Show answer
The delay occurs in stage 5, in main(). The framework has no root widget until runApp is called, so it cannot schedule the first frame. Each await before runApp postpones that call by the duration of the awaited work. The fix is to await only what the first screen needs, or to start the other work after runApp.
Exercise
Name the two halves of producing the first frame and the thread that runs each one. Why does a Stopwatch started in main() and stopped in an addPostFrameCallback underestimate the user's real wait?
Show answer
UI work (build, layout, paint) runs on the UI isolate, and raster work runs on the raster thread. The Stopwatch starts only when main() begins, so it misses process creation, native code, engine load and Dart VM startup. The post-frame callback also fires before the raster thread finishes, so it misses rasterization too.