How to execute code before app exit flutter

后端 未结 3 407
再見小時候
再見小時候 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:12

    What about putting your main/home/top Scaffold widget inside a WillPopScope?

    class MyGreatestApp extends StatefulWidget {
      @override
      _MyGreatestAppState createState() => _MyGreatestAppState();
    }
    
    class _MyGreatestAppState extends State {
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
          child: Scaffold(...),
          onWillPop: _doNastyStuffsBeforeExit,
        );
      }
    
      Future _doNastyStuffsBeforeExit() async{
        // Since this is an async method, anything you do here will not block UI thread
        // So you should inform user there is a work need to do before exit, I recommend SnackBar
    
        // Do your pre-exit works here...
    
        // also, you must decide whether the app should exit or not after the work above, by returning a future boolean value:
    
        return Future.value(true); // this will close the app,
        return Future.value(false); // and this will prevent the app from exiting (by tapping the back button on home route)
      }
    }
    

提交回复
热议问题