老孟导读:在Flutter中如何实现点击2次Back按钮退出App,如何实现App中多个Route(路由),如何实现Back按钮只退出指定页面,此篇文章将告诉你。
WillPopScope用于处理是否离开当前页面,在Flutter中有多种方式能够离开当前页面,好比AppBar、CupertinoNavigationBar上面的返回按钮,点击将会回到前一个页面,在Android手机上点击实体(虚拟)返回按钮,也将会回到前一个页面,此功能对于iOS程序员来讲可能特别容易忽略。git
如下几种状况咱们会用到WillPopScope:程序员
在Android App中最开始的页面点击后退按钮,默认会关闭当前activity并回到桌面,咱们但愿此时弹出对话框或者给出提示“再次点击退出”,避免用户的误操做。微信
WillPopScope( onWillPop: () async => showDialog( context: context, builder: (context) => AlertDialog(title: Text('你肯定要退出吗?'), actions: <Widget>[ RaisedButton( child: Text('退出'), onPressed: () => Navigator.of(context).pop(true)), RaisedButton( child: Text('取消'), onPressed: () => Navigator.of(context).pop(false)), ])), child: Container( alignment: Alignment.center, child: Text('点击后退按钮,询问是否退出。'), ))
咱们也能够把效果作成快速点击2次退出:less
DateTime _lastQuitTime; WillPopScope( onWillPop: () async { if (_lastQuitTime == null || DateTime.now().difference(_lastQuitTime).inSeconds > 1) { print('再按一次 Back 按钮退出'); Scaffold.of(context) .showSnackBar(SnackBar(content: Text('再按一次 Back 按钮退出'))); _lastQuitTime = DateTime.now(); return false; } else { print('退出'); Navigator.of(context).pop(true); return true; } }, child: Container( alignment: Alignment.center, child: Text('点击后退按钮,询问是否退出。'), ))
咱们的App一般是在MaterialApp和CupertinoApp下,MaterialApp和CupertinoApp自己有一个Navigator,因此默认状况下调用Navigator.pop或者Navigator.push就是在操做此Navigator。不过在一些状况下,咱们但愿有本身定义的Navigator,好比以下场景:async
首页:ide
class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { GlobalKey<NavigatorState> _key = GlobalKey(); @override Widget build(BuildContext context) { return Scaffold( body: WillPopScope( onWillPop: () async { if (_key.currentState.canPop()) { _key.currentState.pop(); return false; } return true; }, child: Column( children: <Widget>[ Expanded( child: Navigator( key: _key, onGenerateRoute: (RouteSettings settings) => MaterialPageRoute(builder: (context) { return OnePage(); }), ), ), Container( height: 50, color: Colors.blue, alignment: Alignment.center, child: Text('底部Bar'), ) ], )), ); } }
第一个页面:ui
class OnePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( child: RaisedButton( child: Text('去下一个页面'), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return TwoPage(); })); }, ), ), ), ); } }
第二个页面:this
class TwoPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( child: Text('这是第二个页面'), ), ), ); } }
使用TabView、BottomNavigationBar、CupertinoTabView这些组件时也是同样的原理,只需在每个Tab中加入Navigator,不要忘记指定key。spa
老孟Flutter博客地址(近200个控件用法):http://laomengit.comcode
欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】:
![]() |
![]() |