How do you add query parameters to a Dart http request?
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
If you dont want to override the scheme of base endpoint url, use the below technique to convert the map to query string and append it to the base endpoint url
var endpointUrl = 'https://www.myurl.com/api/v1/user';
Map<String, String> queryParams = {
'param1': '1',
'param2': '2'
};
var headers = {
HttpHeaders.authorizationHeader: 'Token $token',
HttpHeaders.contentTypeHeader: 'application/json',
}
String queryString = Uri.parse(queryParameters: queryParams).query;
var requestUrl = endpointUrl + '?' + queryString; // result - https://www.myurl.com/api/v1/user?param1=1¶m2=2
var response = await http.get(requestUrl, headers: headers);
this is more simpler
final uri = Uri.parse('$baseUrl/v1/endpoint').replace(queryParameters: {
'page': page,
'itemsPerPage': itemsPerPage,
});
final response = await client.get(uri);
Got the same question. The accepted answer won't work if my url is localhost with port like https://localhost:5001
. After spending 1 day to search for solution, I come up with Dio library. Following is my solution using Dio
:
var _dio = new Dio();
var options = new Options;
options.headers['Authorization'] = 'bearer $token';
options.contentType = 'application/json';
String url = "https://www.myurl.com";
Map<String, String> qParams = {
'param1': 'one',
'param2': 'two',
};
var res = await _dio.get(url, options: options, queryParameters: qParams);
Hope this helps.
Use Uri
constructor to build your query, it has a queryParameter
property.
var uri = Uri(
scheme: 'https',
host: 'example.com',
path: '/foo/bar',
fragment: 'baz',
queryParameters: _yourQueryParameters,
);
var response = await http.get(uri);
if (response.statusCode == 200) {
var json = jsonDecode(response.body);
// Do whatever you want to do with json.
}