Sub topic 11
Keeping `main()` and the First Frame Lean
Prerequisites and the startup path
This chapter assumes that you understand Flutter widgets, Dart async and await, and how to run an app from the command line. It also assumes that you have measured startup in profile mode, as described earlier.
When a user taps your app, Flutter performs several tasks before the first usable screen appears:
The first frame is the first complete Flutter frame that the user can see. Work performed before that frame delays the visible result. The goal is not to remove initialization. The goal is to keep only first-screen requirements on the critical path.
Keep `main()` focused
A common mistake is to perform every setup task in main() before calling runApp():
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await initializeDatabase();
await loadRemoteConfig();
await initializeAnalytics();
await refreshTheUserSession();
runApp(const MyApp());
}This code makes the first frame wait for four operations. Even if the first screen does not need all four, the user pays for their combined delay.
Call WidgetsFlutterBinding.ensureInitialized() when you need Flutter bindings before runApp(), such as when initializing a plugin. Then perform only the setup required to construct the first screen. Schedule other work after the first frame:
import 'dart:async';
import 'package:flutter/widgets.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// Keep only first-screen setup here.
runApp(const MyApp());
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(initAnalytics());
});
}
Future<void> initAnalytics() async {
// Start non-critical setup here.
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Center(child: Text('Hello')),
);
}
}addPostFrameCallback runs after Flutter finishes a frame. unawaited starts the asynchronous operation without making main() wait for it. Handle errors inside the operation or with an error-reporting mechanism. Do not use this pattern for work that the first screen must have, such as loading credentials needed to choose the initial route.
Avoid synchronous startup work
Asynchronous code can still block startup if you await it before runApp(). Synchronous code is also dangerous. Large JSON parsing, encryption, image decoding, and database transformations can occupy the UI isolate. While that isolate is busy, it cannot build or paint the first frame.
Move CPU-heavy work out of startup when possible. For work that cannot wait until later, use an isolate. The next chapter covers that technique in detail.
Design the first screen for progress
The first screen does not need to show every piece of data immediately. Render a useful shell with loading states, placeholders, or cached data. Fetch fresh data after the shell appears. This improves perceived startup while the remaining work continues.
Exercise
Why should analytics initialization usually happen after runApp()?
Show answer
Analytics does not normally determine whether the first screen can be built, so awaiting it in main() delays the first frame without improving the initial UI.