You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter命名导航添加多参数:如何从Widget传递userId参数

解决方案

方案一:将userId作为路径参数传递

  1. 更新路由路径定义
    修改router.dart中的路由路径,添加:userId参数:
    CupertinoRoute(
      path: '/report/:index/:userId', // 添加userId路径参数
      page: ReportScreenRoute.page,
    )
    
  2. 重新生成路由代码
    运行AutoRoute代码生成命令:flutter pub run build_runner build,确保router.gr.dart同步更新路径参数映射。
  3. 在Widget中传递参数
    修改navigateNamed调用,将userId拼接到路径中:
    context.router.navigateNamed("/report/$index/$userId") // 拼接userId到路由路径
    

方案二:通过AutoRoute参数类传递(更推荐)

这种方式无需修改路由路径,直接利用生成的路由类传递参数,更贴合AutoRoute的设计规范:

  1. 替换导航方式
    放弃navigateNamed,改用ReportScreenRoute构造函数导航:
    context.router.push(ReportScreenRoute(index: index, userId: userId));
    
  2. 调整参数装饰器
    由于是通过路由参数类传递而非路径参数,修改ReportScreen.dart中的参数装饰:
    const ReportScreen({
      @PathParam('index') this.index,
      this.userId, // 移除@PathParam,适配非路径参数传递
      super.key
    });
    

注意事项

  • 使用路径参数时,需确保userId不含斜杠等路径特殊字符,避免路由解析失败。
  • 每次修改路由定义后,必须重新运行代码生成命令,保证路由代码同步更新。

内容的提问来源于stack exchange,提问作者Gaurav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:05:02