Flutter命名导航添加多参数:如何从Widget传递userId参数
解决方案
方案一:将userId作为路径参数传递
- 更新路由路径定义
修改router.dart中的路由路径,添加:userId参数:CupertinoRoute( path: '/report/:index/:userId', // 添加userId路径参数 page: ReportScreenRoute.page, ) - 重新生成路由代码
运行AutoRoute代码生成命令:flutter pub run build_runner build,确保router.gr.dart同步更新路径参数映射。 - 在Widget中传递参数
修改navigateNamed调用,将userId拼接到路径中:context.router.navigateNamed("/report/$index/$userId") // 拼接userId到路由路径
方案二:通过AutoRoute参数类传递(更推荐)
这种方式无需修改路由路径,直接利用生成的路由类传递参数,更贴合AutoRoute的设计规范:
- 替换导航方式
放弃navigateNamed,改用ReportScreenRoute构造函数导航:context.router.push(ReportScreenRoute(index: index, userId: userId)); - 调整参数装饰器
由于是通过路由参数类传递而非路径参数,修改ReportScreen.dart中的参数装饰:const ReportScreen({ @PathParam('index') this.index, this.userId, // 移除@PathParam,适配非路径参数传递 super.key });
注意事项
- 使用路径参数时,需确保
userId不含斜杠等路径特殊字符,避免路由解析失败。 - 每次修改路由定义后,必须重新运行代码生成命令,保证路由代码同步更新。
内容的提问来源于stack exchange,提问作者Gaurav
相关产品推荐
相关产品推荐

