skip to Main Content

I want to implement a feature where the user can exit the app by pressing the back button twice,
But when i first press the button ‘currentBackPressTime’ and ‘now’ are almost ths same time,ress the button for the second time and after, it works well!. ,what’s wrong with it?
Here is my flutter code:

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);
  static DateTime currentBackPressTime = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      builder: EasyLoading.init(),
      home: WillPopScope(
          onWillPop: () async {
            DateTime now = DateTime.now();
            print(currentBackPressTime);
            print(now);
            if (now.difference(currentBackPressTime) >
                const Duration(milliseconds: 1200)) {
              currentBackPressTime = now;
              EasyLoading.showToast('Press agin to exit!',
                  duration: const Duration(milliseconds: 1200));
              return false;
            }
            return true;
          },
          child: const MyLayout()),
    );
  }
}

I waited for quite some time until the app finished rendering before pressing the button. In theory, there should have been a long time gap between the two events.

2

Answers


  1. class App2 extends StatelessWidget {
      App2({super.key});
      DateTime? lastPressedTime;
    
     @override
     Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          final now = DateTime.now();
          final showExitWarning = lastPressedTime == null ||
              now.difference(lastPressedTime!) >
                  const Duration(milliseconds: 1200);
    
          if (showExitWarning) {
            lastPressedTime = now;
            Fluttertoast.showToast(msg: "Press again to exit");
    
            return false;
          }
    
          return true;
        },
        child: const MyLayout());
    }
    }
    
    Login or Signup to reply.
  2. Your approach is problematic because static variables are initialized lazily, so currentBackPressTime is initialized to the current time the first time it’s accessed, not when your application starts.

    You instead either should:

    • Keep track of the previous time that the back button was pressed, as Aks suggested.

    • Initialize currentBackPressTime to an arbitrary time known to be well into the past (e.g. DateTime(0)).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search