When to persist data in Flutter (onPause equivalent)

Viewed 96

I'm writing a Flutter app geared for mobile devices. I'm used to the Android paradigm where you persist all changes made by the user in onPause, which is basically called whenever the current screen goes into the background. I cannot find a Flutter equivalent.

All examples I see have a "Submit" button of sorts, but I would expect an app to save data when I press the back or home buttons (or if I press a save icon in the app bar).

Where do Flutter apps normally persist the state to storage?

1 Answers

You can use WidgetsBindingObserver to get the AppLifecycleState.paused:

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        break;
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.paused:
        _saveState();
        break;
      case AppLifecycleState.detached:
        break;
    }
  }

  void _saveState() {
    // Save state here
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        body: WillPopScope(
          onWillPop: () async {
            _saveState();
            return true;
          },
          child: SafeArea(
            child: Container(),
          ),
        ),
      );
}

Another option will be to use hydrated_bloc, which will automatically save the state for you.

Related