0

Suppose you want to send an empty search query to an API. For example:

https://api.example.com/search?query=''

In Dart, it makes sense to create this URI with:

final uri = Uri.https('api.example.com', 'search', {'query': ''});

But if you try to print this out: print(uri); you will see:

https://api.example.com/search?query

My current workaround is to wrap double-quotes inside single-quotes (or other way around):

final uri = Uri.https('api.example.com', 'search', {'query': '""'});

which produces this URI:

https://api.example.com/search?query=%22%22

Not a big deal. But still this behavior surprised me as a bit illogical. Who would want to send only a parameter name and not its value? Is it a problem of http library or am I missing something here? Is it the intended behavior and actually serves a purpose?

Ashkan Sarlak
  • 7,124
  • 6
  • 39
  • 51

1 Answers1

0

Was looking for the same use case too. Looked around and ended up with this with some inspiration from the plain javascript implementation.

void main() {
  String fullURL = 'http://api.example.com/search';
  Object queryParameters = {'query': '', 'colour': 'green', 'name': ''};

  String queryString = getQueryString(queryParameters);
  fullURL += '?' + queryString;
  print(fullURL); // http://api.example.com/search?query=&colour=green&name=
}

getQueryString(object) {
    var str = [];
    object.forEach(
      (k, v) => str.add(Uri.encodeComponent(k) + "=" + Uri.encodeComponent(v)),
    );
    return str.join("&");
}
          
Kevin Koo
  • 141
  • 3
  • 5