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

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

    If you want a snackbar you should provide a scaffold key as it's related to a scaffold, so this key should make the trick of calling a snackbar outside of it's scaffold parent.

    Here is a solution :

    class Home extends StatelessWidget {
    
      final GlobalKey _scaffoldKey = new GlobalKey();
    
      @override
      Widget build(BuildContext context) {
      return WillPopScope(
        onWillPop: () async{
            DateTime initTime = DateTime.now();
            popped +=1;
            if(popped>=2) return true;
            await _scaffoldKey.currentState.showSnackBar(
            SnackBar(
                behavior: SnackBarBehavior.floating,
                content: Text('Tap one more time to exit.',textAlign: TextAlign.center,),
                duration: Duration(seconds: 2),
            )).closed;
    
            // if timer is > 2 seconds reset popped counter
            if(DateTime.now().difference(initTime)>=Duration(seconds: 2)) {
            popped = 0;
            }
            return false;
            },
        child: Scaffold(
            key: _scaffoldKey,
            appBar: AppBar(title : Text("Demo")),
            body: Text("body")
        );
      )
    }
    
    

提交回复
热议问题