flutter_crashlytics icon indicating copy to clipboard operation
flutter_crashlytics copied to clipboard

WidgetsFlutterBinding.ensureInitialized(); must be called inside zone

Open passsy opened this issue 6 years ago • 2 comments

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.

passsy avatar Oct 28 '19 13:10 passsy

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 :)

jaumard avatar Oct 28 '19 13:10 jaumard

Also can see https://docs.flutter.dev/testing/errors#errors-not-caught-by-flutter.

linxuebin1990 avatar Mar 18 '22 11:03 linxuebin1990