将WillPopScope替换为PopScope触发'!_debugLocked'异常求助
解决PopScope替换WillPopScope后的'!_debugLocked'异常问题
问题根源
你遇到的异常是因为PopScope的逻辑和WillPopScope完全不同:
- WillPopScope通过
onWillPop的返回值决定是否允许返回,返回false会阻止默认返回行为 - 你当前设置
canPop: true,意味着系统会自动执行返回操作,此时你在对话框里手动调用Navigator.of(context).pop()会和系统的自动pop操作冲突,触发!_debugLocked异常
解决方案
核心思路是阻止系统自动执行pop,完全手动控制返回流程:
- 将
canPop设为false,禁用系统默认的返回行为 - 在
onPopInvoked中触发对话框,由用户操作决定是否返回 - 对话框中按正常逻辑执行两次pop(关闭对话框+返回上页)即可,不会再和系统操作冲突
修改后的完整代码
return PopScope( canPop: false, // 禁用系统自动返回,完全手动控制 onPopInvoked: (bool didPop) async { // 因canPop为false,didPop始终为false,无需处理该分支 if (vStatus[1] && !vStatus[2]) { _showMaterialDialog(context, 1); } }, child: Scaffold( // ... 原有Scaffold内容 ), ); void _showMaterialDialog(BuildContext context, int opt) { showDialog( context: context, builder: (context) { return AlertDialog( title: Text( getTextTitle(opt), style: TextStyle( fontFamily: 'DancingScriptBold', color: Colors.blue, fontSize: 20.0, ), ), content: Text( getTextContent(opt), style: const TextStyle( fontFamily: 'DancingScriptBold', color: Colors.blue, fontSize: 20.0, ), ), actions: <Widget>[ TextButton( onPressed: () { Utils.saveVideo().then((value) { if (value != null && value) { vStatus[2] = true; } // 先关闭对话框,再返回上页 Navigator.of(context).pop(); Navigator.of(context).pop(); }); }, child: const Text( 'Yes', style: TextStyle( fontFamily: 'DancingScriptBold', color: Colors.blue, fontSize: 20.0, ), ), ), TextButton( onPressed: () { // 关闭对话框后返回上页 Navigator.of(context).pop(); Navigator.of(context).pop(); }, child: const Text( 'No', style: TextStyle( fontFamily: 'DancingScriptBold', color: Colors.blue, fontSize: 20.0, ), ), ), ], ); }, ); }
额外说明
- 如果需要在某些条件下允许直接返回(无需弹出对话框),可在
onPopInvoked中判断条件后直接调用Navigator.of(context).pop() - 确保异步操作(如
Utils.saveVideo())完成后再执行pop,避免状态更新不及时
内容的提问来源于stack exchange,提问作者jdevp2
相关产品推荐
相关产品推荐

