TechBuzzPro

How to Execute Code Before App Exit in Flutter

· 5 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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:html or package:universal_html (if targeting multiple platforms).
  • For desktop: platform channels or a plugin like window_manager (optional, for window close events).

Step-by-Step

  1. Understand the lifecycle limitations. Flutter's AppLifecycleState includes detached, 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.
  2. Implement WidgetsBindingObserver in your root widget. Create a stateful widget (e.g., MyApp) and mix in WidgetsBindingObserver. In initState, call WidgetsBinding.instance.addObserver(this);. Override didChangeAppLifecycleState(AppLifecycleState state) and check for AppLifecycleState.detached. Place your cleanup code there. Remember to remove the observer in dispose.
  3. 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 with commit() (synchronous). For network calls, they will likely be cancelled. Instead, queue them for next launch.
  4. For web, use window.onBeforeUnload. In your main() or a web‑specific entry point, import dart:html and set window.onBeforeUnload to 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.
  5. For desktop (Windows, macOS, Linux), listen for window close events. Use a plugin like window_manager or desktop_window to intercept the close button. For example, with window_manager, call WindowManager.instance.setPreventClose(true) and listen to onWindowClose. Then run your cleanup and finally call WindowManager.instance.destroy(). This gives you a reliable hook because the desktop OS waits for the app to close.
  6. 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.
  7. 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 detached handler runs. On web, test closing the tab. Adjust your strategy based on what actually fires.

Common Mistakes

  • Assuming detached always fires. On Android, detached is 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 in didChangeAppLifecycleState, 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. dispose is for widget removal, not app termination; it may not be called when the app is killed.
  • Using web onBeforeUnload for 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 onDestroy in your MainActivity (Kotlin/Java) to call a platform channel, but this is still not guaranteed if the process is killed.
  • For iOS, save state in applicationDidEnterBackground via 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.addObserver early in the app lifecycle (e.g., in main before runApp) 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 onBeforeUnload if no interaction occurred.
  • Desktop close button does nothing. Ensure you have set setPreventClose(true) and are calling destroy() 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.