Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add query parameters to a Dart http request?

How do you correctly add query parameters to a Dart http get request? I been unable to get my request to respond correctly when trying to append the '?param1=one&param2=two' to my url, yet it works correctly in Postman. Here's the gist of my code:

    final String url = "https://www.myurl.com/api/v1/test/";     String workingStringInPostman = "https://www.myurl.com/api/v1/test/123/?param1=one&param2=two";      Map<String, String> qParams = {      'param1': 'one',      'param2': 'two',     };      var res = await http       .get(Uri.encodeFull("$url${widget.pk}/"),       headers: {HttpHeaders.authorizationHeader: "Token $token",          HttpHeaders.contentTypeHeader: "application/json"}, ); 

The ${widget.pk} is simply a integer value being pass (See the value 123 in the workingStringInPostman variable.

The qParams is there for connivence, in case a Uri parameter is needed.

A code example would be welcomed.

like image 447
Peter Birdsall Avatar asked Oct 15 '18 20:10

Peter Birdsall


People also ask

How do I give a parameter query?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.


1 Answers

You'll want to construct a Uri and use that for the request. Something like

final queryParameters = {   'param1': 'one',   'param2': 'two', }; final uri =     Uri.https('www.myurl.com', '/api/v1/test/${widget.pk}', queryParameters); final response = await http.get(uri, headers: {   HttpHeaders.authorizationHeader: 'Token $token',   HttpHeaders.contentTypeHeader: 'application/json', }); 

See https://api.dartlang.org/stable/2.0.0/dart-core/Uri/Uri.https.html

like image 93
Nate Bosch Avatar answered Sep 17 '22 20:09

Nate Bosch