runAppWithReporting static method

Future<void> runAppWithReporting({
  1. required Widget app(),
  2. required ClientConfig config,
  3. bool captureFrameworkErrors = true,
  4. bool capturePlatformDispatcherErrors = true,
  5. bool attachIsolateErrorListener = true,
  6. bool useDefaultFlutterErrorPresentation = true,
})

Initializes reporting and Flutter before building app and calling runApp.

Call this once before initializing Flutter to capture uncaught asynchronous errors in the app's guarded zone. If the widget binding already exists, call this from the zone that initialized it. The app then keeps that zone's asynchronous error handling.

With captureFrameworkErrors, errors pass to FlutterError.presentError by default. Set useDefaultFlutterErrorPresentation to false to invoke the previously installed FlutterError.onError handler instead. With capturePlatformDispatcherErrors, the previous ui.PlatformDispatcher.onError handler retains its return value.

On native platforms, attachIsolateErrorListener listens for uncaught errors on the current isolate. Apps that spawn child isolates must forward those isolates' errors separately.

Implementation

static Future<void> runAppWithReporting({
  required Widget Function() app,
  required ClientConfig config,
  bool captureFrameworkErrors = true,
  bool capturePlatformDispatcherErrors = true,
  bool attachIsolateErrorListener = true,
  bool useDefaultFlutterErrorPresentation = true,
}) async {
  await BugReportClient.instance.initialize(config);

  if (captureFrameworkErrors) {
    final previous = FlutterError.onError;
    FlutterError.onError = (FlutterErrorDetails details) {
      try {
        if (useDefaultFlutterErrorPresentation) {
          FlutterError.presentError(details);
        } else {
          previous?.call(details);
        }
      } finally {
        _report(() => FlutterErrorException(details));
      }
    };
  }

  if (capturePlatformDispatcherErrors) {
    final previous = ui.PlatformDispatcher.instance.onError;
    ui.PlatformDispatcher.instance.onError =
        (Object error, StackTrace stack) {
      try {
        return previous?.call(error, stack) ?? true;
      } finally {
        _reportUncaught(error, stack);
      }
    };
  }

  if (attachIsolateErrorListener) {
    listenForIsolateErrors(_reportUncaught);
  }

  if (_existingBinding() != null) {
    try {
      runApp(app());
    } catch (error, stack) {
      _reportUncaught(error, stack);
    }
  } else {
    runZonedGuarded<void>(() {
      WidgetsFlutterBinding.ensureInitialized();
      runApp(app());
    }, _reportUncaught);
  }
}