Bidev
AdvancedAsync Programming

What are Zones in Dart used for?

Short Answer

A Zone is an execution context that lets you intercept and customize behaviors like error handling, print output, and timers for all code running within it — most commonly used to catch otherwise-uncaught async errors app-wide.

Dart's runZonedGuarded() lets you run a block of code (typically your entire main()/runApp() call) inside a zone with a custom error handler, catching errors that would otherwise crash the app silently — particularly errors thrown in async callbacks that aren't wrapped in a try/catch, which a regular try/catch around runApp() wouldn't catch.

This is the standard pattern for wiring up crash reporting (Firebase Crashlytics, Sentry) so genuinely unhandled async errors still get reported instead of just appearing in the console or crashing silently in release mode.

Code Example

void main() {
  runZonedGuarded(() {
    runApp(const MyApp());
  }, (error, stackTrace) {
    // report to Crashlytics/Sentry
  });
}

Common Mistakes

  • ×Assuming a top-level try/catch around runApp() catches all async errors — it doesn't catch errors in callbacks scheduled after the initial synchronous call completes.
  • ×Not also setting FlutterError.onError for framework-level errors — runZonedGuarded alone doesn't catch those; both are typically wired together.

Interview Tips

  • Mention that runZonedGuarded + FlutterError.onError together is the standard 'catch everything for crash reporting' pattern.