Ensuring Completion of Operations During app Termination in Flutter

Viewed 150

Let's say we have a Flutter app where we want to save some persistent data using shared preferences.

(We don't want to save the data persistently every time the user changes it because the UI depends directly on the data, and in order to save it we need to use await async, and that lags the UI), so we use WidgetsBindingObserver to detect when the app goes to the background in order to use that event as an efficient catch-all opportunity to save the data.

So, we have some code like this in the root page of our app:

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.paused) {
      // went to Background
      myPersistentData.instance.write(); // <-------------- this is an async operation
    }
    if (state == AppLifecycleState.resumed) {
      // came back to Foreground
    }
  }

This seems to work, but I'm concerned that the lifecycle could progress beyond "paused" (pause>stop>finish) so quickly that this "trailing" operation doesn't have time to finish... and thus the data would not be saved.

Is this a legitimate concern?

0 Answers
Related