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

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(queryParameters: queryParams).query;var requestUrl = endpointUrl + '?' + queryString; // result - https://www.myurl.com/api/v1/user?param1=1&param2=2var response = await http.get(requestUrl, headers: headers);


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.