如何在 Dart 中的 Uri 查询字符串中复制一个键

How to have a duplicate a key in a Uri query string in Dart

应用程序:Google 映射静态 API

为了添加多个标记,文档说我们只需要设置 markers 查询字符串的多个值

Multiple markers may be placed within the same markers parameter as long as they exhibit the same style; you may add additional markers of differing styles by adding additional markers parameters.

我试过像这样使用 Uri 库:

 final url = new Uri(
      scheme: 'https',
      host: 'maps.googleapis.com',
      path: 'maps/api/staticmap',
      queryParameters: {
        'markers' : 'color:blue|label:C|1.015,1.054',
        'markers' : 'color:red|label:C|1.012,1.057',
      },
    );
 print(url.toString());

但是 dart 不允许这样做。还有其他方法吗?

发生的情况是它只显示一个标记。 (第一个)

A Map 不能包含重复键。但是,Uri 的构造函数确实支持生成具有重复键的查询字符串。来自 the documentation for Uri's constructor:

When queryParameters is used the query is built from the provided map.... A value in the map must be either a string, or an Iterable of strings, where the latter corresponds to multiple values for the same key.

所以你可以这样做:

final url = Uri(
  scheme: 'https',
  host: 'maps.googleapis.com',
  path: 'maps/api/staticmap',
  queryParameters: {
    'markers': [
      'color:blue|label:C|1.015,1.054',
      'color:red|label:C|1.012,1.057'
    ],
  },
);
print(url.toString());

打印:

https://maps.googleapis.com/maps/api/staticmap?markers=color%3Ablue%7Clabel%3AC%7C1.015%2C1.054&markers=color%3Ared%7Clabel%3AC%7C1.012%2C1.057