You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WillPopScope已被弃用,我使用了如下代码,如何替换该废弃组件?

WillPopScope废弃后的替代方案

原有实现代码

你之前基于WillPopScope的实现代码如下:

WillPopScope(
  onWillPop: () => willPopScopeWid(),
  child: Container(
    // SomeCode
  ),
)
willPopScopeWid() {
  setState(() {
    onTapOfVideo = false;
  });
  return Navigator.pop(context);
}

替代方案:使用PopScope

Flutter 3.12及以上版本中WillPopScope已被废弃,官方推荐使用PopScope组件替代。针对你的需求,改写后的代码如下:

PopScope(
  canPop: false, // 禁用默认返回行为,交由自定义逻辑处理
  onPopInvoked: (bool didPop) {
    if (!didPop) {
      setState(() {
        onTapOfVideo = false;
      });
      Navigator.pop(context);
    }
  },
  child: Container(
    // SomeCode
  ),
)

关键说明

  • canPop: false:阻止系统默认的页面弹出逻辑,确保自定义回调能触发
  • onPopInvoked:用户触发返回操作时触发该回调,didPop参数用于判断是否已经完成弹出动作
  • 回调内先更新onTapOfVideo状态,再手动调用Navigator.pop(context)完成页面弹出

内容的提问来源于stack exchange,提问作者Anu Desai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:22:33