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

Flutter中使用go_router ^6.5.0如何处理未知路由?

在Flutter中用go_router ^6.5.0处理未知路由导航

方法一:配置unknownRoute(推荐方案)

初始化GoRouter时,直接通过unknownRoute参数指定未匹配路由时的跳转页面,这是go_router官方推荐的方式:

final goRouter = GoRouter(
  routes: [
    // 这里放你的正常路由配置
    GoRoute(
      path: '/',
      builder: (context, state) => const HomePage(),
    ),
    GoRoute(
      path: '/profile/:userId',
      builder: (context, state) => ProfilePage(userId: state.pathParameters['userId']!),
    ),
  ],
  // 处理未知路由
  unknownRoute: GoRoute(
    path: '*', // 通配符匹配所有未命中的路径
    builder: (context, state) => UnknownRoutePage(
      originalLocation: state.uri.toString(), // 获取用户原本访问的路径
    ),
  ),
);

方法二:用errorBuilder做自定义错误处理

如果需要区分不同类型的路由错误(比如除了路由不存在,还要处理其他导航错误),可以用errorBuilder捕获异常:

final goRouter = GoRouter(
  routes: [
    // 正常路由配置
    GoRoute(path: '/', builder: (context, state) => const HomePage()),
  ],
  errorBuilder: (context, state) {
    // 判断是否是路由未找到的错误
    if (state.error is GoRouterError && state.error!.message.contains('not found')) {
      return UnknownRoutePage(
        originalLocation: state.uri.toString(),
      );
    }
    // 其他错误返回通用错误页
    return const GeneralErrorPage();
  },
);

补充:UnknownRoutePage示例

确保你的UnknownRoutePage能接收并展示原路径参数:

class UnknownRoutePage extends StatelessWidget {
  final String originalLocation;

  const UnknownRoutePage({super.key, required this.originalLocation});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('页面不存在')),
      body: Center(
        child: Text('您访问的路径 "$originalLocation" 不存在'),
      ),
    );
  }
}

注意点

  • unknownRoute的优先级高于errorBuilder,如果同时配置,会优先触发unknownRoute
  • state.uri.toString()能完整获取用户输入的原始路径,包括查询参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:54:58