Sub topic 2
Calling `WidgetsFlutterBinding.ensureInitialized` First
This chapter assumes you know basic Dart syntax, async and await, Future, try and catch, and how runApp starts a Flutter application.
Before installing global error handlers, initialize Flutter's binding:
void main() {
WidgetsFlutterBinding.ensureInitialized();
// Install error handlers here.
runApp(const MyApp());
}The binding is the connection between Flutter's framework and the platform that runs the app. It coordinates services such as:
- Widget scheduling and rendering.
- Platform messages and plugin calls.
- The application lifecycle.
- Text input, accessibility, and other system services.
- The
FlutterErrorreporting mechanism.
WidgetsFlutterBinding.ensureInitialized() creates this connection if it does not already exist. If it has already been created, the method returns the existing binding instead of creating another one.
Why initialization comes first
A simple Flutter app often calls only runApp in main. Flutter initializes the binding as part of that process. However, code that runs before runApp might need Flutter services. This includes error handlers, plugin initialization, configuration loading, and calls that use platform channels.
Calling ensureInitialized explicitly makes the order clear:
- Initialize Flutter's framework and platform connection.
- Install error handlers.
- Initialize services that depend on Flutter.
- Call
runApp.
flowchart TD
A[Application starts] --> B[ensureInitialized]
B --> C[Install error handlers]
C --> D[Initialize plugins or services]
D --> E[runApp]
E --> F[Flutter builds the widget tree]The binding does not catch every error by itself. It provides the framework context in which Flutter can report framework errors. Later, FlutterError.onError handles errors reported through that framework channel, while PlatformDispatcher.instance.onError handles uncaught errors that escape it.
A complete startup order
The following example uses both error-handler locations. The handlers are only placeholders here; a later chapter can forward these errors to a reporting service.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
debugPrint('Framework error: ${details.exceptionAsString()}');
};
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
debugPrint('Uncaught asynchronous error: $error');
debugPrint('$stack');
return true;
};
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(child: Text('Ready')),
),
);
}
}The first statement ensures that Flutter is ready before the handlers are installed. runApp remains last among the startup operations because it starts building the application's widget tree.
When the call is required
| Situation | Call `ensureInitialized` before it? |
|---|---|
| Calling `runApp` and doing nothing before it | Usually no, because `runApp` initializes it |
| Installing startup error handlers | Yes, as a clear startup convention |
| Calling a plugin before `runApp` | Yes |
| Reading platform configuration before `runApp` | Yes |
| Running a widget test | Use the test binding provided by the test framework |
The call is safe to make more than once. It does not reset the binding or discard existing framework state.
Common ordering mistakes
A frequent mistake is performing plugin work before initialization:
void main() {
// A plugin call may fail because the binding is not ready.
// await SomePlugin.initialize();
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}Move the binding call above any plugin or platform operation. Also avoid installing handlers after runApp unless there is a specific reason. Errors can occur during startup, so late installation may miss them.
ensureInitialized also does not replace try and catch. Use local error handling when the caller can recover, such as retrying a failed network request. Global handlers are a final reporting path for errors that were not handled elsewhere.
Exercise
Why should WidgetsFlutterBinding.ensureInitialized() appear before plugin initialization and global error-handler setup?
Show answer
It creates or retrieves the framework binding, which connects Flutter to platform services and makes those startup operations safe to perform.