Home > Blockchain >  I can't exit app with back button in Flutter
I can't exit app with back button in Flutter

Time:09-06

 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?

CodePudding user response:

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

CodePudding user response:

When you navigate from LoginScreen() to any other screen use

Navigator.pushReplacement<void, void>(
  context,
  MaterialPageRoute<void>(
    builder: (BuildContext context) => const YourScreenName(),
  ),
);

or use get navigation

Get.offAll(YourScreenName());

In this case it will not back to LoginScreen() and you exist from App

  • Related