Flutter 中禁用系统的返回

624 阅读1分钟

使用 PopScope 小组件。这个小组件可以拦截系统的返回按钮事件,并根据自定义的逻辑来决定是否允许返回。

const PopScope({
  super.key,
  required this.child,
  this.canPop = true,
  this.onPopInvoked,
});

在想要禁用返回的的页面添加用 PopScope

Widget build(BuildContext context) {
  return PopScope(
    canPop: true, // 是否允许用户返回
   // 不管是否返回都会调用 onPopInvoked
    onPopInvoked: (didPop) {
   //返回成功 didPop为true,返回失败 didPop为false,
      if(didPop){
        BotToast.showText(text: "返回成功");

      }else{
        BotToast.showText(text: "返回成失败");

      }

    },
    child: Scaffold(appBar: AppBar(title: Text( "PopScope"),),)
  );
}