Convert String to GET request Parameter in Dart using standard library


I have a multiword String that I’d like to convert to a GET request parameter.

I have an API endpoint /search that takes in the parameter query. Now typically your request would look like http://host/search?query=Hello+World.

I have a String Hello World that I’d like to convert to this URL encoded parameter.

Ofcourse, I could just write the logic to break it into words and add a + in between but I was wondering if the URI class could help with this

I’m using Dart’s httpClient to make a request.

Future<String> _getJsonData(String queryToSearch) async {
  List data = new List();
  var httpClient = new HttpClient();

  var request = await httpClient.getUrl(Uri.parse(
      config['API_ENDPOINT'] + '/search?query=' +

  var response = await request.close();
  if (response.statusCode == HttpStatus.OK) {
    var jsonString = await response.transform(utf8.decoder).join();
    data = json.decode(jsonString);
    return data[0].toString();
  } else {
    return "{}";

Essentially, need to encode queryToSearch as the URL parameter.


You can use Uri.http(s) which wrap everythings (query, host, and path) together and encode them accordingly.

    final uri = new Uri.http(config['API_ENDPOINT'], '/search', {"query": queryToSearch});

Answered By – Rémi Rousselet

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *