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

前端 未结 9 528
野趣味
野趣味 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:13

    If the condition is that the user presses only twice, you can use the first solution of course. If you want to increase the number of times you click, you can use this solution. Where the user has to press 3 times within two seconds so he can get out

      DateTime currentBackPressTime;
      /// init counter of clicks
      int pressCount=1;
    

    then :

    Future onWillPop() async {
    
      DateTime now = DateTime.now();
    
    
    
    /// here I check if number of clicks equal 3
    if(pressCount!=3){
    
      ///should be assigned at the first click.
      if(pressCount ==1 )
        currentBackPressTime = now;
      pressCount+=1;
    
    
      return Future.value(false);
      }else{
      if (currentBackPressTime == null ||
          now.difference(currentBackPressTime) > Duration(seconds: 2)) {
    
    
        currentBackPressTime = now;
        pressCount=0;
    
      
        return Future.value(false);
      }
     }
    
    
     return Future.value(true);
    }
    

提交回复
热议问题