dartflutter

How to write a double back button pressed to exit app using flutter


I'm new to flutter, and I saw many android apps can exit when double press back button.

The first time press back button, app shows a toast"press again to exit app". The following second press, app exits. Of course, the time between two press must be not long.

How to do it in flutter?


Solution

  • This is an example of my code (I've used "fluttertoast" for showing toast message, you can use snackbar or alert or anything else)

    DateTime currentBackPressTime;
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        ...
        body: WillPopScope(child: getBody(), onWillPop: onWillPop),
      );
    }
    
    Future<bool> onWillPop() {
        DateTime now = DateTime.now();
        if (currentBackPressTime == null || 
            now.difference(currentBackPressTime) > Duration(seconds: 2)) {
          currentBackPressTime = now;
          Fluttertoast.showToast(msg: exit_warning);
          return Future.value(false);
        }
        return Future.value(true);
      }