Sub topic 11
Keeping main() and the first frame lean
This chapter assumes you can run a Flutter app in profile mode and read flutter run --profile --trace-startup output, which the previous chapter on measuring startup covered. It also assumes you are comfortable with async/await, Future, and the difference between awaiting a call and starting it without waiting.
Why main() sets your startup time
Dart code runs on the UI isolate. The user sees the first Flutter frame only after the engine has started, main() has run, runApp has attached the root widget, and the framework has built, laid out, painted and rasterized one frame. Every await you place before runApp delays that frame by however long the awaited work takes. The framework cannot draw anything until your code reaches runApp.
The goal is simple: before runApp, do only what the first screen cannot draw without. Everything else runs after the first frame, or the first time a feature needs it.
Auditing what main() does today
Start by listing every line that runs before runApp, including work hidden inside package initializers and await calls. Then classify each item.
| Task | Typical placement | Reason |
|---|---|---|
| `WidgetsFlutterBinding.ensureInitialized()` | Before `runApp` if you call platform channels first | Plugins that use method channels need the binding. `runApp` calls it itself otherwise. |
| Reading the saved theme or locale | Before `runApp`, if the first frame depends on it | Without it, the screen flashes the wrong theme. |
| Crash reporting setup | Before `runApp` | It must catch errors from startup onward. Pay the cost deliberately. |
| Analytics, remote config, push token registration | After the first frame | The first screen does not draw from them. |
| Opening a local database | Lazily, or after the first frame | Open it when the first query needs it. |
| Pre-fetching network data | After the first frame | A network call can take far longer than a frame. |
| Parsing large JSON or other bulk data | In an isolate | See the chapter on isolates. |
Two rules help with borderline cases. If skipping a task would cause a visible glitch on the first screen, keep it before runApp. If skipping it would only delay a feature the user has not reached yet, move it later.
A typical slow main() looks like this:
import 'package:flutter/widgets.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await initCrashReporting();
await initAnalytics();
await initRemoteConfig();
await openDatabase();
await prefetchFeed();
runApp(const MyApp());
}
Future<void> initCrashReporting() async {}
Future<void> initAnalytics() async {}
Future<void> initRemoteConfig() async {}
Future<void> openDatabase() async {}
Future<void> prefetchFeed() async {}
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 five awaits run one after another. If each takes 80 ms, the user waits 400 ms before the framework starts building anything. The fix is not to make each task faster. It is to stop making the first frame wait for them.
Moving work after the first frame
WidgetsBinding.instance.addPostFrameCallback registers a callback that runs once, after the current frame has been drawn. Registering it right after runApp gives you "after the first frame" semantics. Wrap the call in unawaited from dart:async to show that you are deliberately not waiting for it.
import 'dart:async';
import 'package:flutter/material.dart';
class Analytics {
Analytics._();
static final Analytics instance = Analytics._();
Future<void>? _ready;
/// Safe to call many times. The setup runs once, and concurrent
/// callers share the same Future.
Future<void> ensureInitialized() => _ready ??= _init();
Future<void> _init() async {
// Stands in for real setup such as loading config or opening a socket.
await Future<void>.delayed(const Duration(milliseconds: 300));
}
Future<void> track(String event) async {
await ensureInitialized();
debugPrint('track: $event');
}
}
void main() {
runApp(const MyApp());
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(Analytics.instance.ensureInitialized());
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => Analytics.instance.track('button_tapped'),
child: const Text('Tap'),
),
),
),
);
}
}The important detail is ensureInitialized storing the Future in _ready. If the user taps the button before the post-frame setup finishes, track waits on the same in-flight initialization instead of starting a second one. If nobody ever calls the service, the setup still runs once after the first frame. You can drop the post-frame call and the service becomes purely lazy.
What can stay slow without hurting you
Not every await is harmful. await Future.delayed or a network call inside a function that runs after runApp does not block the UI, because the isolate returns to its event loop while the future is pending. The cost is CPU time on the UI isolate, not waiting time. So the audit question is "how much synchronous Dart code runs before the first frame", more than "how many awaits".
Keeping the first build cheap
main() is only half of the first frame. The first build, layout and paint also run on the UI isolate. Common causes of a slow first frame:
- A home screen that builds a long list eagerly. Use
ListView.builderor slivers so only visible items are built. - Large images decoded at full size. Pass
cacheWidthorcacheHeighttoImage.assetorImage.networkso the decoder produces a smaller bitmap. - Work in
initStateorbuild, such as sorting a list, parsing a string, or reading from a store synchronously. Move it out, or start it as a future and show a placeholder until it completes. - A first screen that waits for a network response before showing anything. Draw the layout first, with a skeleton or an empty state, and fill in the data when it arrives.
A cheap first screen can render a placeholder, for example const SizedBox.shrink() or a progress indicator, while a FutureBuilder or state object loads data. That trades a short loading state for a much earlier first frame. A user who sees a frame in 300 ms and data at 900 ms generally perceives the app as faster than one that shows nothing for 900 ms.
Trade-offs and failure modes
- Race conditions. Code that assumed a service was initialized in
main()can now run before it. The memoizedensureInitializedpattern above prevents most of these. Direct use of a half-initialized global does not. - Lost early errors. If you move crash reporting after the first frame, exceptions thrown during startup go unreported. Keep error handlers installed before
runApp, even if heavy configuration happens later. - Plugin ordering. Some plugins need to be configured before the first widget uses them. If a screen reads a plugin on its first build, that plugin belongs before
runApp. - Moving cost, not removing it. Deferring a 200 ms task shifts it to after the first frame. If the user can interact immediately and the task blocks the UI isolate, they feel a stutter instead of a slow launch. Measure the frame times after launch too, not only time to first frame.
- Debug mode lies. Startup in debug mode includes JIT compilation and assertions. Only compare numbers from profile mode on a real device, as covered earlier in this tutorial.
Verifying the change
Run the same measurement before and after each change, one change at a time:
flutter run --profile --trace-startupCompare the time-to-first-frame values in build/start_up_info.json, and repeat the run several times, because a single launch varies with device state and caches. If a change does not move the number beyond that variation, it was not on your critical path, so you can revert it to keep the code simple.
Exercise
A teammate's main() awaits initAnalytics() and loadSavedTheme() before calling runApp. The first screen draws with the saved theme. Which call should stay before runApp and which should move, and why?
Show answer
Keep loadSavedTheme() before runApp, because the first frame depends on it and skipping it would flash the wrong theme. Move initAnalytics() after the first frame, for example with addPostFrameCallback and unawaited, because the first screen does not need it to draw.
Exercise
You moved a 250 ms synchronous JSON parse from main() into a post-frame callback. Time to first frame improved, but users now report a stutter right after launch. Why, and what should you do?
Show answer
Post-frame callbacks run on the UI isolate, so the synchronous parse blocks the next frames and causes jank. The cost moved instead of disappearing. Run the parse in an isolate, for example with Isolate.run, so the UI isolate stays free to render frames.