WidgetsFlutterBinding.ensureInitialized(); must be called inside zone
I had trouble getting errors reported. Synchronous errors where caught but not asynchronous ones. The problem was that WidgetsFlutterBinding.ensureInitialized() was called outside of the error catching zone.
// doesn't work
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
Zone.current.handleUncaughtError(details.exception, details.stack);
};
await FlutterCrashlytics().initialize();
runZoned<Future<Null>>(() async {
runApp(MyApp());
}, onError: (error, stackTrace) async {
await FlutterCrashlytics().reportCrash(error, stackTrace, forceCrash: false);
});
}
Moving WidgetsFlutterBinding.ensureInitialized() inside runZoned fixes it and now reports all errors.
// works
void main() async {
FlutterError.onError = (FlutterErrorDetails details) {
Zone.current.handleUncaughtError(details.exception, details.stack);
};
runZoned<Future<Null>>(() async {
WidgetsFlutterBinding.ensureInitialized();
await FlutterCrashlytics().initialize();
runApp(MyApp());
}, onError: (error, stackTrace) async {
await FlutterCrashlytics().reportCrash(error, stackTrace, forceCrash: false);
});
}
I think the Readme should get an update.
Hey @passsy thanks for the report, look super weird !! because from the doc https://api.flutter.dev/flutter/widgets/WidgetsFlutterBinding/ensureInitialized.html once it's called it's done, so it shouldn't mind having it outside the zone.
When I have some time I'll update the readme, keep this one opened until it's done :)
Also can see https://docs.flutter.dev/testing/errors#errors-not-caught-by-flutter.