双击/在Flutter中单击onBack按钮时,我需要关闭我的应用程序

时间:2019-05-23 10:34:10

标签: dart flutter flutter-layout

我是扑朔迷离的新手,我看到双击后退按钮时,许多android应用程序都可以退出。

第一次按下后退按钮,应用程序显示吐司“再次按下以退出应用程序”。在第二次按下时,应用程序退出。当然,两次按下之间的时间不能太长。

我使用了这段代码,但是没有用。请帮助我

    Future<bool> _onWillPop() {
  return showDialog(
    context: ctx,
    builder: (ctx) => new AlertDialog(
      title: new Text('Confirm Exit?',
          style: new TextStyle(color: Colors.black, fontSize: 20.0)),
      content: new Text(
          'Are you sure you want to exit the app? Tap \'Yes\' to exit \'No\' to cancel.'),
      actions: <Widget>[
        new FlatButton(
          onPressed: () {
            // this line exits the app.
            SystemChannels.platform
                .invokeMethod('SystemNavigator.pop');
          },
          child:
          new Text('Yes', style: new TextStyle(fontSize: 18.0)),
        ),
        new FlatButton(
          onPressed: () => Navigator.pop(ctx), // this line dismisses the dialog
          child: new Text('No', style: new TextStyle(fontSize: 18.0)),
        )
      ],
    ),
  ) ??
      true;
}

2 个答案:

答案 0 :(得分:0)

这是一个示例代码:它使用-“ fluttertoast”来显示吐司。

DateTime currentBackPressTime = DateTime.now();

Future<bool> onWillPop() {
    DateTime now = DateTime.now();
    if (now.difference(currentBackPressTime) > Duration(seconds: 2)) {
      currentBackPressTime = now;
      Fluttertoast.showToast(msg: 'Tap Again to Exit'); // you can use snackbar too here
      return Future.value(false);
    }
    return Future.value(true);
  }

答案 1 :(得分:0)

它运行完美。

 Future<bool> _onWillPop() {
  return showDialog(
    barrierDismissible: false,
    context: ctx,
    builder: (context) => new AlertDialog(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12.0)),
      content: new Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Icon(
                 Icons.exit_to_app,
                color: MyColor.PrimaryColor,
                size: 25.0,
              ),
              SizedBox(width: 8.0),
              Expanded(
                child: Text(
                  "Do you want to exit this App",
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 17.0,
                      color: Colors.black),
                ),
              ),
            ],
          ),

      actions: <Widget>[
        new FlatButton(
          onPressed: ()
          {
            Navigator.of(context).pop(false); },
          child: new Text('No',style: TextStyle(color: MyColor.PrimaryColor,fontSize: 17.0)),
        ),

        new FlatButton(
          onPressed: () {
            Navigator.pop(context,true);
            Navigator.of(context).pop(true);},
          child: new Text('Yes',style: TextStyle(color:MyColor.PrimaryColor,fontSize: 17.0)),
        ),
      ],
    ),
  ) ?? false;



}