如何修复GoRouter.of(context).pop()使其正确返回上一页?
GoRouter.pop() 跳转异常问题排查
以下是几种可能的原因及解决办法:
路由跳转方式错误
如果其他页面是通过context.go()或context.pushReplacement()进入的,路由栈不会保留上一页的记录,调用pop()就会直接回到根路由。需要改用context.push()跳转,这样新页面会被添加到路由栈顶部,pop()就能正常返回上一页。
代码示例:// 错误跳转方式 onPressed: () => context.go('/other-page'), // 正确跳转方式 onPressed: () => context.push('/other-page'),嵌套路由配置不规范
若其他页面属于嵌套路由的子页面,但路由配置未正确设置父路由的Navigator,会导致pop()无法识别父路由栈。检查GoRouter的路由配置,确保嵌套结构正确,比如使用ShellRoute或嵌套GoRoute来维护路由层级:GoRouter( routes: [ ShellRoute( builder: (context, state, child) => Scaffold(body: child), routes: [ GoRoute( path: '/main', builder: (context, state) => MainPage(), routes: [ GoRoute( path: 'other', builder: (context, state) => OtherPage(), ), ], ), ], ), ], );Context 上下文不正确
如果调用GoRouter.of(context)时使用的是全局context或父组件的context,pop()会作用在根Navigator上,直接回到主屏幕。确保使用当前页面组件的上下文,可通过Builder组件包裹按钮来获取正确的context:Builder( builder: (context) => ElevatedButton( onPressed: () => GoRouter.of(context).pop(), child: const Text('返回'), ), );
内容的提问来源于stack exchange,提问作者Elena Epshtein
相关产品推荐
相关产品推荐

