首页 > 解决方案 > 手机的后退按钮无法正常工作

问题描述

当我单击后退按钮时,在我的 Flutter 应用程序中关闭。我使用了 onWillpopscope() 但它对我不起作用。我在下面分享我的代码。但是当我创建一个示例项目时,它正在工作。谁能解释一下为什么它在现有应用程序中不起作用。谁能建议我如何实现这一目标。

class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  State<StatefulWidget> createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future<bool> _onBackPressed() {
    return showDialog(
          context: context,
          builder: (context) => new AlertDialog(
                title: new Text('Are you sure?'),
                content: new Text('Do you want to exit an App'),
                actions: <Widget>[
                  new GestureDetector(
                    onTap: () => Navigator.of(context).pop(false),
                    child: roundedButton("No", const Color(0xFF167F67),
                        const Color(0xFFFFFFFF)),
                  ),
                  new GestureDetector(
                    onTap: () => Navigator.of(context).pop(true),
                    child: roundedButton(" Yes ", const Color(0xFF167F67),
                        const Color(0xFFFFFFFF)),
                  ),
                ],
              ),
        ) ??
        false;
  }

  Widget roundedButton(String buttonLabel, Color bgColor, Color textColor) {
    var loginBtn = new Container(
      padding: EdgeInsets.all(5.0),
      alignment: FractionalOffset.center,
      decoration: new BoxDecoration(
        color: bgColor,
        borderRadius: new BorderRadius.all(const Radius.circular(10.0)),
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: const Color(0xFF696969),
            offset: Offset(1.0, 6.0),
            blurRadius: 0.001,
          ),
        ],
      ),
      child: Text(
        buttonLabel,
        style: new TextStyle(
            color: textColor, fontSize: 20.0, fontWeight: FontWeight.bold),
      ),
    );
    return loginBtn;
  }

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
      onWillPop: _onBackPressed,
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text(
            "On Back pressed",
            style: new TextStyle(color: Colors.white),
          ),
        ),
        body: new Center(
          child: new Text("Home Page"),
        ),
      ),
    );
  }
}

在 Pubspec 中:

version: 1.0.0+1
environment:
  sdk: ">=2.0.0-dev.68.0 <3.0.0"

标签: flutter

解决方案


像这样更改因为child已弃用,请使用builder

Future<bool> _onWillPop() {
return showDialog(
  context: context,
  builder: (context) => new AlertDialog(
    title: new Text('Are you sure?'),
    content: new Text('Unsaved data will be lost.'),
    actions: <Widget>[
      new FlatButton(
        onPressed: () => Navigator.of(context).pop(false),
        child: new Text('No'),
      ),
      new FlatButton(
        onPressed: () => Navigator.of(context).pop(true),
        child: new Text('Yes'),
      ),
    ],
  ),
) ?? false;
}

推荐阅读