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
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)
}
}