Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't exit app with back button in Flutter

 DateTime timeBackPressed = DateTime.now(); 

WillPopScope(
      onWillPop: () async {
        final difference = DateTime.now().difference(timeBackPressed);
        final isExit = difference >= Duration(seconds: 2);
        timeBackPressed = DateTime.now();

        if (isExit) {
          Fluttertoast.showToast(msg: 'Exit App');

          return false;
        } else {
          Fluttertoast.cancel();
          return true;
        }
      },

This code is in my LoginScreen. I added this page as home in main.dart.When opening the application, my LoginScreen page opens. When I press the back button 2 times, it gives the message Toast and when I press the 2nd time, I can exit the application. But the problem is that when I add this code to my other pages, when I press the back button, it doesn’t do any control and goes back to the previous page.

While on other pages, LoginScreen returns when I press it once or exit the application when I press it twice like this code. How can I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

try this:

var presscount = 0;
@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        presscount++;

        if (presscount == 2) {
          exit(0);
        } else {
          var snackBar =
              SnackBar(content: Text('press another time to exit from app'));
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
          return false;
        }
      },
      child: Scaffold(
        backgroundColor: Colors.red,
        body: Container(),
      ),
    );
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading