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

Flutter导航报错!_debugLocked:使用createVehicle增改数据遇问题求助

解决Flutter Navigator报错:'!_debugLocked': is not true

这个错误的核心原因是:在Navigator处于锁定状态(正在处理导航操作)时,发起了新的导航指令。你的代码中,异步请求完成后连续调用两次Navigator.pop(context),如果第一次关闭弹窗的操作还未完成就触发第二次页面关闭操作,就会触发该断言失败。

修复方案

方案1:延迟导航操作至当前UI帧完成

通过WidgetsBinding.instance.addPostFrameCallback确保导航操作在当前帧绘制完成后执行,避免在导航锁定期发起操作:

createVehicle(data) {
  progressDialogue(context);
  VehicleService().createVehicle(data).then((onValue) {
    // 关闭加载弹窗
    Navigator.pop(context);
    if (onValue['status']) {
      if (onValue['message'] == "success") {
        showToast("${"Successfully".tr} ${widget.edit ? "Update".tr : "Created".tr}");
        // 延迟执行页面返回,确保导航状态解锁
        WidgetsBinding.instance.addPostFrameCallback((_) {
          Navigator.pop(context);
        });
      } else {
        showToast("Already Exist!".tr);
      }
    } else {
      showToast("Something Went Wrong!".tr);
    }
  });
}

方案2:使用rootNavigator确保上下文正确

如果加载弹窗是通过全局导航器弹出的,明确指定rootNavigator: true获取正确的导航实例,避免上下文混乱:

createVehicle(data) {
  // 替换progressDialogue为标准showDialog,确保导航上下文正确
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (_) => const Center(child: CircularProgressIndicator()),
  );
  VehicleService().createVehicle(data).then((onValue) {
    // 关闭弹窗
    Navigator.of(context, rootNavigator: true).pop();
    if (onValue['status']) {
      if (onValue['message'] == "success") {
        showToast("${"Successfully".tr} ${widget.edit ? "Update".tr : "Created".tr}");
        Navigator.pop(context);
      } else {
        showToast("Already Exist!".tr);
      }
    } else {
      showToast("Something Went Wrong!".tr);
    }
  });
}

额外注意点

  • 若当前组件是StatefulWidget,异步操作完成后可先通过mounted判断页面是否仍存在,避免操作已销毁的上下文:
    if (mounted) {
      Navigator.pop(context);
    }
    
  • 确保progressDialogue的实现基于标准Flutter弹窗组件(如showDialog),避免自定义上下文操作导致的状态异常。

内容的提问来源于stack exchange,提问作者muhammad afzaal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:40:01