ckot
ckot

Reputation: 359

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?

Upvotes: 2

Views: 3402

Answers (1)

eamirho3ein
eamirho3ein

Reputation: 17880

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(),
      ),
    );
  }

Upvotes: 4

Related Questions