skip to Main Content

I am trying to enhance the user experience by preventing accidental app exits. If users press the back button once, they should see a toast message saying, "Press again to exit." If they press the back button again within 2 seconds, the app should exit. If more than 2 seconds pass, the app should reset the back button by pressing the counter.

2

Answers


  1. Define a variable DateTime? _lastPressedAt;

    Create a logic with WillPopScope.

     WillPopScope(
          onWillPop: () async {
            final now = DateTime.now();
            if (_lastPressedAt == null || now.difference(_lastPressedAt!) > Duration(seconds: 2)) {
              _lastPressedAt = now;
              Fluttertoast.showToast(
                msg: "Press again to exit",
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.BOTTOM,
              );
              return false; // Prevent the app from exiting
            }
            return true; // Exit the app
          },
          child: Scaffold(
            appBar: AppBar(
              title: Text("Double Back to Exit"),
            ),
            body: Center(
              child: Text("Press back button twice within 2 seconds to exit"),
            ),
          ),
        );
    
    Login or Signup to reply.
  2. This should work. Let me know if it works for you.

    You can a achieve a "double back press for exit" with a Future and a ValueNotifier.

    class MyScreen extends StatefulWidget {
      const MyScreen({super.key});
    
      @override
      State<MyScreen> createState() => _MyScreenState();
    }
    
    class _MyScreenState extends State<MyScreen> {
      final ValueNotifier<bool> _backPressAllowed = ValueNotifier(false);
    
      @override
      Widget build(BuildContext context) {
        return ValueListenableBuilder<bool>(
          valueListenable: _backPressAllowed,
          builder: (BuildContext context, bool backPressAllowed, Widget? child) {
            return PopScope(
              canPop: backPressAllowed,
              onPopInvoked: (didPop) {
                if (!didPop) {
                  _allowBackPress();
                }
              },
              child: const Scaffold(
                body: Text("my screen"),
              ),
            );
          },
        );
      }
    
      Future<void> _allowBackPress() async {
        _backPressAllowed.value = true;
    
        await Future.delayed(const Duration(milliseconds: 2000));
    
        _backPressAllowed.value = false;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search