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

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

    The first time press back button, app shows a AlertDialog"press yes to exit app and press No to can't exit application". This is an example of my code (I've used 'AlertDialog')

       @override
          Widget build(BuildContext context) {
    
            return new WillPopScope(
              onWillPop: _onBackPressed,
              child: DefaultTabController(
                initialIndex: _selectedIndex,
                length: choices.length,
                child: Scaffold(
                  appBar: AppBar(
    
                    ),
                  ),
    
              ),
            );
          }
             Future _onBackPressed() {
            return showDialog(
              context: context,
              builder: (context) {
                return AlertDialog(
                  title: Text('Are you sure?'),
                  content: Text('Do you want to exit an App'),
                  actions: [
                    FlatButton(
                      child: Text('No'),
                      onPressed: () {
                        Navigator.of(context).pop(false);
                      },
                    ),
                    FlatButton(
                      child: Text('Yes'),
                      onPressed: () {
                        Navigator.of(context).pop(true);
                      },
                    )
                  ],
                );
              },
            ) ?? false;
          }
    

提交回复
热议问题