手机的后退按钮无法正常工作

时间:2019-06-08 10:10:55

标签: flutter

在我的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"

1 个答案:

答案 0 :(得分:0)

由于e已被弃用,因此需要进行更改,请使用child

builder