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

Flutter应用报错no routes for location: /level1,路由导航失效求助

解决GoRouter跳转/level1报错"no routes for location: /level1"的问题

问题重现

点击按钮调用GoRouter.of(context).go('/level1')跳转时,抛出异常:Exception: no routes for location: /level1,相关代码如下:

跳转按钮代码:

child: FilledButton(
  onPressed: () => GoRouter.of(context).go('/level1'),
  style: TextButton.styleFrom(
    primary: Color(0xFF000000),
    fixedSize: Size(157, 40),
    backgroundColor: Color(0xFFFF8383)
  ), // Background Color
  child: const Text('START')
),

路由配置片段:

GoRoute(
  path: '/level1',
  builder:(context, state) => Level1Screen(key: Key('level1')),
),

Level1Screen定义:

class Level1Screen extends StatefulWidget {
  const Level1Screen({super.key});

  @override
  State<Level1Screen> createState() => _Level1ScreenState();
}

class _Level1ScreenState extends State<Level1Screen> {
  static final _log = Logger('level1');
  // ... 其他代码
}

排查与解决方法

  • 确认路由已添加到GoRouter的routes列表
    单独的GoRoute定义不会生效,必须将其包含在GoRouter初始化时的routes数组中。完整的GoRouter配置应该类似:

    final GoRouter _router = GoRouter(
      routes: <RouteBase>[
        // 根路由(必须配置)
        GoRoute(
          path: '/',
          builder: (context, state) => const HomeScreen(),
        ),
        // 你的level1路由
        GoRoute(
          path: '/level1',
          builder:(context, state) => const Level1Screen(key: Key('level1')),
        ),
      ],
    );
    
  • 确认MaterialApp使用了GoRouter的配置
    必须通过MaterialApp.router关联GoRouter,而非普通的MaterialApp:

    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp.router(
          title: 'Flutter Demo',
          theme: ThemeData(primarySwatch: Colors.blue),
          routerDelegate: _router.routerDelegate,
          routeInformationParser: _router.routeInformationParser,
          routeInformationProvider: _router.routeInformationProvider,
        );
      }
    }
    
  • 检查Level1Screen的导入与拼写
    确保Level1Screen所在文件已正确导入到main.dart中,类名、路由路径/level1无拼写错误(路径大小写敏感)。

  • 确认跳转时的Context在GoRouter作用域内
    按钮所在组件必须是MaterialApp.router的子组件,保证GoRouter.of(context)能获取到正确的路由实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 21:22:49