6

I want to send parameters with an http GET request in dart. The first answer here demonstrates it well: How do you add query parameters to a Dart http request?

var uri =
    Uri.https('www.myurl.com', '/api/query', queryParameters);

However, a major problem is that queryParameters only accepts:

Map<String, String>

This doesn't allow me to pass in lists/arrays.

If i change my get request to a post request, I am easily able to send a body (as a json encoded String) as outlined by the flutter docs: https://pub.dev/documentation/http/latest/http/post.html

post(url, {Map<String, String> headers, body, Encoding encoding})

However, the get request has no such equivalent argument for query parameters: https://pub.dev/documentation/http/latest/http/get.html

get(url, {Map<String, String> headers})

I have also tried adding query parameters directly to the url like so:

get('www.myurl.com/api/query/?array[]=value1&array[]=value2&array[]=value3)

but the square brackets [] always get transformed into %5B%5D when I receive it in the server.

Any help is appreciated. Thanks

wei
  • 557
  • 1
  • 10
  • 24

1 Answers1

11

In fact, queryParameter takes Map<String, dynamic>. Check the source code:

  factory Uri(
      {String scheme,
      String userInfo,
      String host,
      int port,
      String path,
      Iterable<String> pathSegments,
      String query,
      Map<String, dynamic /*String|Iterable<String>*/ > queryParameters,
      String fragment}) = _Uri;

The dynamic can be either a String or an Iterable<String>. So,

  var uri = Uri(
    scheme: 'http',
    host: 'www.myurl.com',
    path: '/api/query/',
    queryParameters: {
      'array': ['value1', 'value2', 'value3'],
    },
  );
  print(uri);

prints:

http://www.myurl.com/api/query/?array=value1&array=value2&array=value3
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
  • That `[]` suffix is a kludge for PHP servers. Doesn't the server accept the URL encoded form? (The only place in a URL that unescaped bracket is allowed is an IPv6 address.) – Richard Heap Aug 06 '19 at 02:00
  • whoops i just deleted my comment since i realized my server was reading %5B%5D as []. So everything is now working well. Thanks for your help – wei Aug 06 '19 at 02:12