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

Dart shelf_route:带多参数GET请求的正确路由配置问询

问题解决方案

1. 正确的路由名称

你之前混淆了路径参数和查询参数的写法:shelf_router里的<id>语法是用来匹配路径中的参数(比如/test/123这种URL),但你的请求是通过?id=null传递的查询参数,所以正确的路由路径应该是"/test",不需要在路径中添加参数占位符。

修改后的服务器路由代码:

final _route = shelf_router.Router()
  ..get("/test", (Request request) {
    // 从URL查询参数中获取id
    String? id = request.url.queryParameters['id'];
    return Response.ok('ok, id: $id');
  })
  ..all('/<ignored|.*>', (Request request) {
    return Response.notFound('notFound');
  });

2. 支持任意数量参数的路由配置

如果要接收任意多个查询参数,路由依然使用"/test"即可——所有查询参数都会被自动解析到request.url.queryParameters这个Map中,直接通过键名就能获取对应的值,无需在路由路径中提前声明:

..get("/test", (Request request) {
  // 获取所有查询参数
  Map<String, String> allParams = request.url.queryParameters;
  // 按需获取单个参数
  String? name = allParams['name'];
  int? age = int.tryParse(allParams['age'] ?? '');
  return Response.ok('received params: $allParams');
})

额外提示

你的Flutter代码里有个小语法错误:

// 原代码少了结尾的单引号
String url= 'http://localhost:8080/test;
// 修正后
String url= 'http://localhost:8080/test';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:40:39