runZonedGuarded Function in Flutter

Gaurav Swarankar
2 min readJan 7, 2024

--

Hi Readers today we are going to discuss on runZonedGuarded function in flutter.
runZonedGuarded is function which is used to implement block of code within special zone. This function helps you to handle any uncaught exceptions that may occur during the execution of that code.

We have 2 methods in dart.

  1. runZoned
  2. runZonedGuarded

Difference between runZoned and runZonedGuarded is in error handling. runZoned captures errors and exceptions but does not prevent the app from crashing. On the other hand, runZonedGuarded captures errors, allows you to handle them gracefully, and then prevents the app from crashing.

Let’s go step by step for the implementation.

So now we are going to handle exception and after that we will send that exception to firebase. for this we will add firebase_crashlytics package in our project.

dependencies:
flutter:
sdk: flutter
firebase_core: ^2.24.2
firebase_crashlytics: ^3.4.9

we will wrap your entire app within a function that captures errors. Our function will takes two arguments: a callback function and an error handler function.

void main() {
runZonedGuarded(() {
WidgetsFlutterBinding.ensureInitialized();

FlutterError.onError = (FlutterErrorDetails details) {
catchUnhandledExceptions(details.exception, details.stack);
};

runApp(const MainApp());

}, catchUnhandledExceptions);
}
void catchUnhandledExceptions(Object error, StackTrace? stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
debugPrintStack(stackTrace: stack, label: error.toString());
}

If any unhandled error occurs during the app’s execution, it will be caught by the catchUnhandledExceptions method.

Conclusion

Error handling is an essential part of app development in Flutter. The runZonedGuarded function to capture and handle uncaught errors, preventing your app from crashing. This improve app stability.

Hope you enjoyed this article!

Clap 👏 If this article helps you.

See you all again soon!

--

--

Gaurav Swarankar

Mobile application developer | Flutter | dart | Getx | API | Mobility | Bloc |