Search code examples
androidflutterdartexit

I tried to do exit the app on second tap using Popscope but it didn't work on the way I expected, It didn't even exit


late int selectedIndex; DateTime? currentPress;

Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) async {
        if(selectedIndex != 0){
          setState(() {
            selectedIndex = 0;
          });
          return Future.value(null);
        } else {
          final now = DateTime.now();
          if(currentPress == null || now.difference(currentPress!) > const Duration(seconds: 2)){
            currentPress = now;
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('Press back again to exit'),
                duration: Duration(seconds: 1),
              ),
            );
            return Future.value(null);
          } else {
            return;
          }
        }
      },
      ),
    );
  }

how to I change the code exit the app at the second click. I tried canpop =true but it exit the app on first click and Removed the async from the function and return void from all the condition also doesn't work.


Solution

  • Try this

    
    return PopScope(
          canPop: false,
          onPopInvoked: (didPop) async {
            if (selectedIndex != 0) {
              setState(() {
                selectedIndex = 0;
              });
              return;
            } else {
              final now = DateTime.now();
              if (currentPress == null ||
                  now.difference(currentPress!) > const Duration(seconds: 2)) {
                currentPress = now;
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Press back again to exit'),
                    duration: Duration(seconds: 1),
                  ),
                );
                return;
              } else {
                SystemNavigator.pop();
              }
            }
          },
          child: // Your Widget
        );