GoRouter断言失败求助:routeInformation.state不能为空
GoRouter断言失败(
'routeInformation.state != null')排查与修复 核心原因
该错误源于初始路由对应的routeInformation.state为空,通常和闪屏页作为首屏的路由配置、GoRouter初始化参数设置不当有关。
排查与修复步骤
1. 确认初始路由配置
确保闪屏页被明确设置为GoRouter的初始路由,且路由定义存在:
final GoRouter _router = GoRouter( // 明确指定闪屏页路径为初始路由 initialLocation: '/splash', routes: [ // 闪屏页路由定义必须存在 GoRoute( path: '/splash', builder: (context, state) => SplashPage(), ), GoRoute( path: '/home', builder: (context, state) => HomePage(), ), ], );
避免将初始路由设为未定义的路径,或依赖redirect间接跳转闪屏页(易触发state为空问题)。
2. 检查自定义解析器(若有)
如果使用了自定义RouteInformationParser,需确保处理初始路由时不为state返回空值:
class AppRouteParser extends RouteInformationParser<RouteState> { @override Future<RouteState> parseRouteInformation(RouteInformation info) async { final uri = Uri.parse(info.location ?? '/splash'); // 为初始路由提供默认state,避免空值 return RouteState(uri, info.state ?? {}); } }
3. 修正闪屏页跳转逻辑
闪屏页自动跳转主页时,需在initState中执行,避免build阶段重复触发路由变更:
class SplashPage extends StatefulWidget { @override State<SplashPage> createState() => _SplashPageState(); } class _SplashPageState extends State<SplashPage> { @override void initState() { super.initState(); // 延迟跳转主页,确保路由初始化完成 Future.delayed(const Duration(seconds: 2), () { GoRouter.of(context).go('/home'); }); } @override Widget build(BuildContext context) { return Scaffold(body: Center(child: CircularProgressIndicator())); } }
4. 验证MaterialApp.router配置
确保正确关联GoRouter的核心组件:
MaterialApp.router( routerDelegate: _router.routerDelegate, routeInformationParser: _router.routeInformationParser, routeInformationProvider: _router.routeInformationProvider, );
内容的提问来源于stack exchange,提问作者Ashen madalagama
相关产品推荐
相关产品推荐

