Flutter学习中的问题记录: 如何监听实体/虚拟返回键和AppBar返回键

效果GIF

《Flutter学习中的问题记录: 如何监听实体/虚拟返回键和AppBar返回键》 route.gif

解决

WillPopScope

class RoutePageWithValue extends StatelessWidget {
  final String lastPageName;

  BuildContext context;

  RoutePageWithValue(this.lastPageName);

  _showDialog() {
    showDialog<Null>(
      context: context,
      child: new AlertDialog(content: new Text('退出当前界面'), actions: <Widget>[
        new FlatButton(
            onPressed: () {
              Navigator.pop(context);
              Navigator.of(context).pop();
            },
            child: new Text('确定'))
      ]),
    );
  }

  Future<bool> _requestPop() {
    _showDialog();
    return new Future.value(false);
  }

  @override
  Widget build(BuildContext context) {
    this.context = context;
    //监听左上角返回和实体返回
    return new WillPopScope(
        child: new Scaffold(
            appBar: new AppBar(
              title: new Text('RoutePageWithValue'),
              centerTitle: true,
            ),
            body: new Center(
              child: new Text('$lastPageName'),
            )),
        onWillPop: _requestPop);
  }
}



如果当前是栈内最后一个页面,或者主界面

 _showDialog() {
    showDialog<Null>(
      context: context,
      child: new AlertDialog(content: new Text('退出app'), actions: <Widget>[
        new FlatButton(
            onPressed: () {
              Navigator.pop(context);
              if (Navigator.canPop(context)) {
Navigator.pop(context);
} else { 
SystemNavigator.pop();

}
            },
            child: new Text('确定'))
      ]),
    );
  }

已有项目集成到Flutter代码已经上传到我的GITHUB

知乎日报Flutter版代码已经上传到我的GITHUB

基础学习过程中的代码都放在GITHUB

每天学一点,学到Flutter发布正式版!

    原文作者:老实巴交的读书人
    原文地址: https://www.jianshu.com/p/f9f496652807
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞