kiwi-bop / flutter_crashlytics

:package: Flutter plugin for Crashlytics integration
BSD 2-Clause "Simplified" License
194 stars 46 forks source link

WidgetsFlutterBinding.ensureInitialized(); must be called inside zone #95

Open passsy opened 4 years ago

passsy commented 4 years ago

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.

jaumard commented 4 years ago

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

linxuebin1990 commented 2 years ago

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