使用auto_route时无法导航到MainPage的嵌套路由问题排查
问题分析与修复方案
核心错误点
- 路由名称不匹配:路由配置中定义的主路由名称是
MainPageRouter,但闪屏页代码中调用pushNamed('MainPage'),名称不一致导致找不到目标路由。 - 路由结构设计错误:将主页面等核心路由作为SplashPage的子路由不合理,闪屏页是一次性启动页,不应作为其他页面的父路由容器。
- 重复Path冲突:
HomeRouter和BrandsRouter的path都设为pages,会导致路由匹配冲突;子路由的path设置重复(如HomePage的path也为pages),会生成无效路径/pages/pages。
修正后的路由配置
@MaterialAutoRouter( replaceInRouteName: 'Page,Router', routes: [ // 闪屏页作为初始路由 AutoRoute( path: '/', page: SplashPage, initial: true, ), // 主页面路由容器(用于底部导航) AutoRoute( path: '/main', name: 'MainPageRouter', page: EmptyRouterPage, children: [ // 首页(子路由path设为空,作为MainPageRouter的默认页面) AutoRoute(path: '', page: HomePage), // 品牌页 AutoRoute(path: 'brands', page: BrandsPage), // 个人中心容器 AutoRoute( path: 'profile', name: 'UsersRouter', page: EmptyRouterPage, children: [ AutoRoute(path: '', page: ProfileBody), AutoRoute(path: 'account', page: AccountPageInfo), AutoRoute(path: 'card', page: CridetCardPage), ], ), ], ), ], ) class $AppRouter {}
修正后的闪屏页代码
class SplashPage extends StatefulWidget { const SplashPage({Key? key}) : super(key: key); @override State<SplashPage> createState() => _SplashPageState(); } class _SplashPageState extends State<SplashPage> { Timer? _timer; @override void initState() { super.initState(); _timer = Timer(const Duration(seconds: 3), () { // 使用replace替换路由栈,避免用户返回闪屏页,同时使用正确的路由名称 AutoRouter.of(context).replaceNamed('MainPageRouter'); // 也可以直接使用生成的路由类(更安全,避免拼写错误): // AutoRouter.of(context).replace(const MainPageRouter()); }); } @override void dispose() { _timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Center( child: Image.asset("assets/splash.gif"), ); } }
额外注意事项
- 修正后需运行
flutter pub run build_runner build重新生成auto_route的路由代码。 - 底部导航栏的页面切换,需基于
MainPageRouter这个EmptyRouterPage的子路由进行管理,使用AutoRouter.of(context).push或replace完成切换。
内容的提问来源于stack exchange,提问作者Sally
相关产品推荐
相关产品推荐

