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

在firebase-get-to-know-flutter step_02中遇_AssertionError:No GoRouter found in context

解决GoRouter未在Context中找到的报错问题

可能原因及解决思路

  • Context层级不匹配:点击RSVP按钮时使用的Context未包含GoRouter的InheritedWidget。检查导航触发代码的Context来源——如果按钮嵌套在Builder、StatefulWidget的深层子组件中,确保使用的是能访问到GoRouter的Context,或通过GlobalKey获取顶层有效Context。
  • GoRouter初始化位置错误:确认GoRouter是在App顶层Widget(如MaterialApp.router)中配置的,且整个Widget树能继承到其Context。检查main.dart里的MaterialApp.router配置,确保routerConfig正确指向GoRouter实例,没有在中间层级隔断上下文传递。
  • 异步操作中Context失效:如果RSVP点击事件包含异步逻辑(比如Firebase请求),不要在异步回调中使用原Context(此时Widget可能已销毁)。提前在同步代码中获取GoRouter实例:
    final router = GoRouter.of(context);
    // 执行异步操作
    someFirebaseCall().then((_) {
      router.push('/targetRoute');
    });
    
  • 依赖配置问题:检查pubspec.yaml中是否正确添加go_router依赖,版本是否与codelab要求一致,执行flutter pub get确保依赖安装完成。
  • 动态Widget的Context丢失:若RSVP按钮在动态生成的Widget(如列表项)中,确认每次构建时Context有效,未因状态变化导致上下文被替换。

快速排查步骤

  1. 打开main.dart,验证MaterialApp.router的routerConfig是否正确关联GoRouter对象。
  2. 在按钮点击的同步代码中尝试调用GoRouter.of(context),若此时就报错,说明当前Context确实无法访问GoRouter。
  3. 尝试用Builder包裹按钮,通过Builder提供的Context获取GoRouter:
    Builder(
      builder: (context) {
        return ElevatedButton(
          onPressed: () => GoRouter.of(context).push('/rsvp'),
          child: const Text('RSVP'),
        );
      },
    )
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:40:34