【问题标题】:Http get query parameters from different listsHttp从不同列表中获取查询参数
【发布时间】:2023-04-03 17:20:01
【问题描述】:

我需要发出一个 HTTP GET 请求来检索一些过滤后的数据。 我的 API 接受 3 个参数数组,在我的代码中我有 3 个不同的参数列表。 是否可以从 3 个 int 列表中创建包含具有相同键和不同值的参数的 Map?

Future<List<Tour>> fetchFilteredTours(List<int> bikeTypeIds,
      final List<int> difficultyIds, final List<int> locationIds) async {
    final Map<String, String> qryParams = {
    };

    //How to create my qryParams with all arrays values?
    //Something like
    qryParams.add(Map.fromIterable(bikeTypeIds, key: (e) => 'bikeTypeId', value: (e) => e));

    final response = await http
        .get(Uri.http('myDomain', '/api/search/tours', qryParams));

    return parseResponse(response);
  }

想要的结果是{{protocol}}://{{url}}/api/search/tours?bikeTypeId=1&amp;bikeTypeId=2&amp;difficultyId=1&amp;locationId=1

【问题讨论】:

  • 使用String,而不是Map
  • 是的,我可以使用字符串。但我的是一个map 研究案例
  • 你希望 qryParams ['bikeTypeId'] 返回什么?
  • 问题不是我想返回什么,而是Uri.http() 接受什么。它接受Map&lt;String,String&gt;,但在地图中您不能放置具有相同键的条目

标签: flutter dart


【解决方案1】:
  final keys = ['bikeTypeId', 'difficultyId', 'locationId'];

  final values = [bikeTypeIds, difficultyIds, locationIds].map(
    (ids) => ids.map((e) => e.toString()),
  );

创建一个将给定键与值相关联的 Map 实例。

  final qryParams = Map.fromIterables(keys, values);

从其组件创建一个新的 URI。

  Uri(scheme: 'https', host: 'myDomain', path: 'api/search/tours', queryParameters: qryParams);

【讨论】:

  • Uri(host: 'myDomain', path: 'api/search/tours', queryParameters: qryParams); 不支持 http/s 域。在我的请求中,我指定了Uri.http(),因为我的是一个 HTTP GET 请求。我的域名类似于http://www.example.com
【解决方案2】:

试试qryParams.add(Map.fromIterable(bikeTypeIds, key: (e) =&gt; 'bikeTypeId', value: (e) =&gt; '$e'))

这将提供Uri.http 所需的Map&lt;String, String&gt;。在您的代码中,您试图创建一个Map&lt;String, int&gt; ...注意'$e'

【讨论】:

  • 嗨,布莱恩,感谢'$e'。这是一个愚蠢的错误。主要问题是map.add()方法不存在
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 2019-01-23
相关资源
最近更新 更多