In this example, we will learn how to write a double back button pressed to exit app using flutter This is an example of my code (I’ve used “fluttertoast” for showing toast message, you can use snackbar or alert or anything else)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | DateTime currentBackPressTime; @override Widget build(BuildContext context) { return Scaffold( ... body: WillPopScope(child: getBody(), onWillPop: onWillPop), ); } Future<bool> onWillPop() { DateTime now = DateTime.now(); if (currentBackPressTime == null || now.difference(currentBackPressTime) > Duration(seconds: 2)) { currentBackPressTime = now; Fluttertoast.showToast(msg: exit_warning); return Future.value(false); } return Future.value(true); } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.