Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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=' +
          queryToSearch));

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

Essentially, need to encode queryToSearch as the URL parameter.

like image 921
bholagabbar Avatar asked Apr 18 '18 11:04

bholagabbar


People also ask

Can we convert string to int in Dart?

A string can be cast to an integer using the int. parse() method in Dart. The method takes a string as an argument and converts it into an integer.


2 Answers

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});
like image 75
Rémi Rousselet Avatar answered Oct 17 '22 05:10

Rémi Rousselet


The Uri class provides methods for that

  • https://api.dartlang.org/stable/1.24.3/dart-core/Uri/encodeQueryComponent.html
  • https://api.dartlang.org/stable/1.24.3/dart-core/Uri/encodeFull.html
  • https://api.dartlang.org/stable/1.24.3/dart-core/Uri/encodeComponent.html
like image 3
Günter Zöchbauer Avatar answered Oct 17 '22 04:10

Günter Zöchbauer