Flutter ShellRoute使用报错:未找到对应Widget
问题解决:ShellRoute使用子路由报错
错误原因
你遇到的报错是因为ShellRoute的子路由使用了绝对路径(/register),导致GoRouter无法在ShellRoute的上下文里匹配到该路由,而是直接去顶级路由查找,从而找不到对应的页面生成器。
修正步骤
- 把ShellRoute子路由的
path改为相对路径,去掉开头的/,即从/register改为register - 给ShellRoute本身设置一个根路径
path: '/',确保子路由的路径能正确匹配
修正后的完整代码示例
final GlobalKey<NavigatorState> _shellNavigatorKey = GlobalKey<NavigatorState>(); GoRouter router = GoRouter( routes: [ ShellRoute( navigatorKey: _shellNavigatorKey, path: '/', // 为ShellRoute设置根路径 builder: (context, state, childpage) { return Scaffold( appBar: AppBar( elevation: 0, centerTitle: true, automaticallyImplyLeading: true, backgroundColor: const Color(0xffffffff), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.zero, ), title: const Text( 'test', style: TextStyle( fontWeight: FontWeight.w700, fontStyle: FontStyle.normal, fontSize: 18, color: Color(0xff000000), ), ), leading: IconButton( icon: const Icon( Icons.arrow_back, color: Color(0xff212435), size: 24, ), onPressed: () { GoRouter.of(context).pop(); }, ), ), backgroundColor: const Color(0xffffffff), body: Center(child: childpage), ); }, routes: <RouteBase>[ GoRoute( path: 'register', // 使用相对路径,去掉开头的/ name: 'Register', builder: (context, state) => const Register(), ), ], ), ], );
额外检查
确保_shellNavigatorKey已经正确初始化(如代码中所示),避免因导航键未设置导致的其他异常。
内容的提问来源于stack exchange,提问作者ralphy
相关产品推荐
相关产品推荐

