如何在Dialog中通过GoRouter正确实现页面跳转?
解决GoRouter在Dialog中跳转报错"No GoRouter found in context"的问题
核心原因
Dialog的builder函数生成的上下文(dialogContext)属于弹窗自身的独立上下文,没有包含GoRouter的InheritedWidget依赖,因此直接用该上下文调用context.go()会触发找不到GoRouter的断言错误。
解决方案
方案一:提前获取GoRouter实例
在弹出Dialog前,从当前页面的上下文获取GoRouter实例,后续在Dialog的确认回调中直接使用该实例完成跳转:
// 在页面build方法中提前获取GoRouter实例 final goRouter = GoRouter.of(context); // 弹出确认Dialog showDialog( context: context, builder: (dialogContext) { return AlertDialog( title: const Text('确认返回?'), actions: [ TextButton( onPressed: () => Navigator.pop(dialogContext), child: const Text('取消'), ), TextButton( onPressed: () { // 先关闭Dialog Navigator.pop(dialogContext); // 使用提前获取的GoRouter实例跳转回目标路由 goRouter.go(previousRoute); }, child: const Text('确定'), ), ], ); }, );
方案二:直接使用GoRouter的pop方法(仅返回上一页场景)
如果只是需要返回上一页,无需指定具体路由路径,可以直接调用GoRouter实例的pop()方法,无需传入目标路由:
final goRouter = GoRouter.of(context); showDialog( context: context, builder: (dialogContext) { return AlertDialog( title: const Text('确认返回?'), actions: [ TextButton( onPressed: () => Navigator.pop(dialogContext), child: const Text('取消'), ), TextButton( onPressed: () { Navigator.pop(dialogContext); // 直接返回上一页 goRouter.pop(); }, child: const Text('确定'), ), ], ); }, );
内容的提问来源于stack exchange,提问作者Dan12314
相关产品推荐
相关产品推荐

