How to Execute Code Before App Exit in Flutter
In this article
To run code before your Flutter app exits, you cannot rely on a single cross‑platform "onExit" callback. On Android, use WidgetsBindingObserver to detect AppLifecycleState.detached and perform cleanup, but be aware the OS may kill the process without warning. On iOS, the system generally does not allow asynchronous work after the app is backgrounded, so save critical data earlier. For desktop and web, you can use window.onBeforeUnload (web) or platform channels (desktop) to run synchronous cleanup. The most reliable approach is to persist state continuously and treat any exit hook as a best‑effort extra.
What You'll Need
- Flutter SDK installed and a project set up (any platform: Android, iOS, web, or desktop).
- Basic familiarity with Dart and Flutter widgets.
- For web: access to
dart:htmlorpackage:universal_html(if targeting multiple platforms). - For desktop: platform channels or a plugin like
window_manager(optional, for window close events).
Step-by-Step
- Understand the lifecycle limitations. Flutter's
AppLifecycleStateincludesdetached, which is emitted when the app is still hosted but detached from the engine (e.g., before destruction). However, on Android and iOS the OS can terminate the process without calling any Dart code. So treat any exit handler as a bonus, not a guarantee. - Implement
WidgetsBindingObserverin your root widget. Create a stateful widget (e.g.,MyApp) and mix inWidgetsBindingObserver. IninitState, callWidgetsBinding.instance.addObserver(this);. OverridedidChangeAppLifecycleState(AppLifecycleState state)and check forAppLifecycleState.detached. Place your cleanup code there. Remember to remove the observer indispose. - Keep cleanup synchronous and fast. In
didChangeAppLifecycleState, avoid long‑running async operations. If you must save data, use synchronous file writes (e.g.,File.writeAsStringSync) or shared preferences withcommit()(synchronous). For network calls, they will likely be cancelled. Instead, queue them for next launch. - For web, use
window.onBeforeUnload. In yourmain()or a web‑specific entry point, importdart:htmland setwindow.onBeforeUnloadto a function that returns a string (to show a confirmation dialog) or performs synchronous cleanup. Note: modern browsers restrict what you can do here; only synchronous operations are allowed, and returning a non‑null string triggers a generic confirmation prompt. - For desktop (Windows, macOS, Linux), listen for window close events. Use a plugin like
window_managerordesktop_windowto intercept the close button. For example, withwindow_manager, callWindowManager.instance.setPreventClose(true)and listen toonWindowClose. Then run your cleanup and finally callWindowManager.instance.destroy(). This gives you a reliable hook because the desktop OS waits for the app to close. - Persist critical data continuously. Because exit hooks are unreliable, save user progress, settings, and state as they change (e.g., on every form submission or via a debounced autosave). Use
shared_preferences,hive, or a local database. This way, even a sudden kill loses at most a few seconds of data. - Test on real devices. Use Android's "Don't keep activities" developer option to simulate process death, and on iOS use the task switcher to swipe the app away. Observe whether your
detachedhandler runs. On web, test closing the tab. Adjust your strategy based on what actually fires.
Common Mistakes
- Assuming
detachedalways fires. On Android,detachedis not guaranteed when the user swipes the app from recents; the process may be killed outright. - Performing async work in lifecycle callbacks. The framework does not wait for
Futures indidChangeAppLifecycleState, so async cleanup may be cut off. - Forgetting to remove the observer. This can cause memory leaks or callbacks on disposed widgets.
- Relying on
dispose()for app exit.disposeis for widget removal, not app termination; it may not be called when the app is killed. - Using web
onBeforeUnloadfor async saves. Browsers block asynchronous operations during unload; only synchronous code runs.
Tips
- Use a combination of lifecycle observers and periodic autosave for robustness.
- On Android, you can also override
onDestroyin yourMainActivity(Kotlin/Java) to call a platform channel, but this is still not guaranteed if the process is killed. - For iOS, save state in
applicationDidEnterBackgroundvia a platform channel, as the app may be terminated while in background. - Keep cleanup code idempotent—it may run multiple times or not at all.
- Use
WidgetsBinding.instance.addObserverearly in the app lifecycle (e.g., inmainbeforerunApp) to catch all events.
Troubleshooting
- My cleanup code never runs on Android. This is expected when the app is force‑stopped or swiped away. Rely on continuous saving instead.
- The app crashes on exit. Check for null references or async operations in your lifecycle handler. Wrap cleanup in try‑catch and avoid awaiting.
- Web confirmation dialog doesn't appear. Browsers require a user gesture before showing the dialog; also, some browsers ignore
onBeforeUnloadif no interaction occurred. - Desktop close button does nothing. Ensure you have set
setPreventClose(true)and are callingdestroy()after cleanup; otherwise the window may not close. - Observer not receiving events. Verify you added the observer and that your widget is still mounted. Use a global observer if needed.
Frequently Asked Questions
Can I run async code before the app exits?
Generally no. Lifecycle callbacks are synchronous, and the OS may terminate the process without waiting. Use synchronous operations or save data earlier.
Does AppLifecycleState.detached fire on iOS?
It can fire when the app is about to be destroyed, but iOS often kills the app from the background without notice. Do not rely on it for critical saves.
How do I detect app exit on Flutter web?
Use window.onBeforeUnload from dart:html. Return a string to show a confirmation dialog, and perform only synchronous cleanup.
Is there a package that handles exit reliably?
No package can override OS behavior. Packages like window_manager help on desktop, but mobile remains best‑effort.
What about dispose()?
dispose() is called when a widget is removed from the tree, not when the app exits. It is not a reliable exit hook.
Can I use platform channels to run native code on exit?
Yes, but the same limitations apply: native code may not run if the process is killed. Use it only for best‑effort cleanup.