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

前端 未结 9 472
野趣味
野趣味 2020-12-24 13:39

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

9条回答
  •  醉梦人生
    2020-12-24 14:17

    This is my solution, you can change backPressTotal value to the number of pressed you want!

    int backPressCounter = 0;
    int backPressTotal = 2;
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        ...
        body: WillPopScope(child: getBody(), onWillPop: onWillPop),
      );
    }
    
    Future onWillPop() {
        if (backPressCounter < 2) {
          Fluttertoast.showToast(msg: "Press ${backPressTotal - backPressCounter} time to exit app");
          backPressCounter++;
          Future.delayed(Duration(seconds: 1, milliseconds: 500), () {
            backPressCounter--;
          });
          return Future.value(false);
        } else {
          return Future.value(true);
        }
    }
    

提交回复
热议问题