The Flutter bindings were initialized in a different zone than is now being used

67 Views Asked by At

I'm getting an error related to Flutter bindings being initialized in a different zone.

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  MyApp app = MyApp();

// Run the whole app in a zone to capture all uncaught errors.

  runZonedGuarded(() => runApp(app), (Object error, StackTrace stackTrace) {
    if (isInDebugMode) {
      print(error);
      print(stackTrace);
      print('In dev mode. Not sending report to Sentry.io.');
      return;
    }

    SentryClient? sentryClient =
        app.myProviderKey.currentState?.sentryClient;

    try {
      sentryClient?.captureException(
        error,
        stackTrace: stackTrace,
      );
      print('Error sent to sentry.io: $error');
    } catch (e) {
      print('Sending report to sentry.io failed: $e');
      print('Original error: $error');
    }
  });
}

I've added

WidgetsFlutterBinding.ensureInitialized();

at the start of main() because of an error I encountered earlier which is

Unhandled Exception: Binding has not yet been initialized.

The above error has disappeared but the Zone error has cropped up. Help appreciated.

1

There are 1 best solutions below

6
Ivo On BEST ANSWER

Move it to inside the runZonedGuarded, like:

Future<void> main() async {
  MyApp? app;
  // Run the whole app in a zone to capture all uncaught errors.

  runZonedGuarded((){
      WidgetsFlutterBinding.ensureInitialized();
      app = MyApp();
      runApp(app!);
    }, (Object error, StackTrace stackTrace) {
    if (isInDebugMode) {
      print(error);
      print(stackTrace);
      print('In dev mode. Not sending report to Sentry.io.');
      return;
    }

    SentryClient? sentryClient =
        app?.myProviderKey.currentState?.sentryClient;

    try {
      sentryClient?.captureException(
        error,
        stackTrace: stackTrace,
      );
      print('Error sent to sentry.io: $error');
    } catch (e) {
      print('Sending report to sentry.io failed: $e');
      print('Original error: $error');
    }
  });
}