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

Flutter导航异常:调用Navigator.push无法跳转至目标页面

Flutter导航无响应但操作执行成功的问题排查与解决

问题描述

代码中无法导航至LocalFilesPage,但showLoadingAlertDialog可正常显示运行,终端输出结果也显示操作执行成功。

已尝试的解决方法

  • 使用物理设备测试
  • 确保Widget树中的context有效
  • 通过debugPrint验证输出结果正确
  • 确认LocalFilesPage可正常运行
  • 尝试切换flutter_bloc版本至8.1.0和8.1.5

相关代码

Future<void> addImageCameraGalleryCubit(context, {required String fileName}) async {
emit(AddImageLoading());
showLoadingAlertDialog(context, 'Uploading Image please wait...', true);

try {
  final result = await addCameraGalleryImageUseCase.call(fileName);
  debugPrint('>>> 2 RES $result');
  Navigator.push(context, MaterialPageRoute(builder: (context) => LocalFilesPage()));
  emit(AddImageSuccess(file: result));

} catch (e) {
  emit(AddImageFailure());
  buildAlertDialog(context, 'Error', 'Failed to add image', true);
}
}

终端输出

I/flutter (20651): >>> 2 RES File: '/data/user/0/com.redjaguarapps.fusion/cache/image_cropper_1712684502739.png'

可行解决方向

  1. 关闭加载弹窗后执行导航
    当前showLoadingAlertDialog作为弹窗会占用当前context的导航栈,导致Navigator.push无法生效。需先关闭弹窗再执行导航:
// 在Navigator.push前添加弹窗关闭逻辑
Navigator.pop(context);
Navigator.push(context, MaterialPageRoute(builder: (context) => LocalFilesPage()));
  1. 使用全局导航Key
    若当前context并非导航器的有效context,可创建GlobalKey<NavigatorState>获取全局导航上下文,确保导航操作生效:
// 全局定义导航Key
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

// 后续使用该Key执行导航
navigatorKey.currentState?.push(MaterialPageRoute(builder: (context) => LocalFilesPage()));
  1. 延迟导航至UI帧完成后
    emit(AddImageSuccess(...))触发的UI重建可能中断导航操作,可通过SchedulerBinding确保导航在UI帧更新后执行:
emit(AddImageSuccess(file: result));
SchedulerBinding.instance.addPostFrameCallback((_) {
  Navigator.push(context, MaterialPageRoute(builder: (context) => LocalFilesPage()));
});
  1. 检查弹窗实现逻辑
    若showLoadingAlertDialog基于showDialog实现,需确认弹窗关闭逻辑是否正确,避免因弹窗未释放context导致导航失败。

内容的提问来源于stack exchange,提问作者DL Studio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:32:36