Flutter中auto_route为仅含命名构造器的类生成路由报错如何解决
Flutter auto_route仅含命名构造器页面生成路由报错解决方案
报错根因
auto_route_generator默认会优先查找页面类的无名称默认构造器生成路由代码,当页面类仅存在命名构造器时,生成器内部找不到目标构造器触发空值校验异常,即日志中出现的Null check operator used on a null value错误。
可用解决方案
方案1:路由定义时指定对应命名构造器(推荐)
如果你需要保留现有三个命名构造器,且三个构造器对应不同的路由跳转场景,可以直接在路由配置中为每个场景绑定对应构造器:
// 你的router.dart路由配置文件 @MaterialAutoRouter( routes: [ // 其他路由... AutoRoute(page: ProfilePage, name: 'ProfileARoute', constructor: 'a'), AutoRoute(page: ProfilePage, name: 'ProfileBRoute', constructor: 'b'), AutoRoute(page: ProfilePage, name: 'ProfileCRoute', constructor: 'c'), ], ) class $AppRouter {}
配置后重新执行路由生成命令,生成器会自动匹配对应名称的构造器生成代码,不会再触发空指针报错。跳转时直接调用对应路由名即可。
方案2:为指定构造器添加路由构造器注解
如果仅需将其中一个命名构造器作为路由的默认入口,可以直接在目标构造器上添加@RouteConstructor注解:
@RoutePage() class ProfilePage extends StatelessWidget { // 标注该构造器为路由生成使用的构造器 @RouteConstructor() ProfilePage.a({ Key? key, this.profileType = UserType.a, required this.a, required this.userProfileId, }) : super(key: key); // 其余命名构造器保持不变 ProfilePage.b({...}); ProfilePage.c({...}); }
方案3:改造为统一默认构造器
如果你不需要拆分多路由入口,可以将现有命名构造器整合为一个带可选参数的默认构造器,添加断言保证参数合法性即可:
@RoutePage() class ProfilePage extends StatelessWidget { final UserType profileType; final A? a; final B? b; final C? c; final String userProfileId; ProfilePage({ Key? key, required this.profileType, this.a, this.b, this.c, required this.userProfileId, }) : assert( (profileType == UserType.a && a != null) || (profileType == UserType.b && b != null) || (profileType == UserType.c && c != null), '对应用户类型的参数不可为空' ), super(key: key); }
注意事项
如果使用的auto_route版本低于3.0,暂不支持构造器指定配置,建议先升级到最新稳定版再使用上述方案。
内容的提问来源于stack exchange,提问作者Sebb
相关产品推荐
相关产品推荐

