How to execute code before app exit flutter

后端 未结 3 406
再見小時候
再見小時候 2020-12-11 03:21

I want to detect when a user quit my app and execute some code before but I don\'t know how to do this. I tried to use this package: https://pub.dev/packages/flutter_lifecyc

3条回答
  •  时光取名叫无心
    2020-12-11 04:06

    You can not do exactly what you want to do right now, anyway, the best approach right now is to check when the application it’s running in background/inactive using the AppLifecycleState from the SDK (basically does what your library is trying to do)

    The library that you are using it’s outdated, since a pull request from November 2019 the AppLifecycleState.suspending it’s called AppLifecycleState.detached.

    You can take a look at the AppLifecycleState enum in the api.flutter.dev website

    Here’s an example of how to observe the lifecycle status of the containing activity:

    import 'package:flutter/widgets.dart';
    
    class LifecycleWatcher extends StatefulWidget {
      @override
      _LifecycleWatcherState createState() => _LifecycleWatcherState();
    }
    
    class _LifecycleWatcherState extends State with WidgetsBindingObserver {
      AppLifecycleState _lastLifecycleState;
    
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        setState(() {
          _lastLifecycleState = state;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        if (_lastLifecycleState == null)
          return Text('This widget has not observed any lifecycle changes.', textDirection: TextDirection.ltr);
    
        return Text('The most recent lifecycle state this widget observed was: $_lastLifecycleState.',
            textDirection: TextDirection.ltr);
      }
    }
    
    void main() {
      runApp(Center(child: LifecycleWatcher()));
    }
    

    I think that deleting your data on the inactive cycle and then creating it again in the resumed one can work for you.

提交回复
热议问题