每个 WillPopScope 仅对当前组件生效,不可在 MaterialApp 上使用。 WillPopScope 返回值为 false时,使用 Navigator.of(context).maybePop()
则不会退出当前路由(比如 AppBar 的退出)。而使用 Navigator.of(context).pop()
依然会退出。 WillPopScope 返回值为 true时,未必会直接退出,还要根据当前页是否是首页来判断。相关代码截图:
在未设置 WillPopScope 的情况下,快速连续点按 Navigator.of(context).maybePop()
可能会经过多次跳转,直到会回到首页。
示例代码:
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
print('d will pop');
return true;
},
child: Scaffold(
appBar: AppBar(
title: Text("home page"),
),
body: Center(
child: Column(
children: [
Text("Home"),
TextButton(
onPressed: () {
Navigator.pushNamed(context, "/me");
},
child: Text("Go To ME"),
),
TextButton(
onPressed: () {
Navigator.of(context).maybePop();
},
child: Text("Exist HOME"),
)
],
),
),
),
);
}
}