How to Add Query Parameters to DART HTTP Request ?

3 min read
How to Add Query Parameters to DART HTTP Request
How to Add Query Parameters to DART HTTP Request

Hope you guys are doing amazing with Flutter. Take a Deep Dive and learn about How to Add Query Parameters to DART HTTP Request.

So are you excited about the same? Let’s get into it.

How to Add Query Parameters to DART HTTP Request?

You’ll want to construct a Uri and use that for the request. Something like the given snippet below:

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

There is a dart package that provides some helper classes for HTTP requests.聽BasicUtils

Install it with the given code snippet like the below:

dependencies:
  basic_utils: ^1.4.0

So you can add a map of headers and query parameters to each request.

// Define some headers and query parameters
Map<String, String> headers = {
  "Accept": "application/json"
};
Map<String, String> queryParameters = {
  "foo": "bar"
};

// Body
String body = "{ 'some':'json'}";

// Send request
Map<String, dynamic> responseData = await HttpUtils.postForJson("api.com/dosomething", body,
      headers: headers, queryParameters: queryParameters);

If you don’t want to override the scheme of the base endpoint URL, use the below technique to convert the map to a 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'
};
String queryString = Uri(queryParameters: queryParams).query;

var requestUrl = endpointUrl + '?' + queryString; // result - https://www.myurl.com/api/v1/user?param1=1&param2=2
var response = await http.get(requestUrl);

Conclusion:

Thank you for reading !!! we hope you have learned. Let your friends and colleagues know about the article and help them grow their knowledge too 馃檪

Keep Learning !!! Keep Fluttering !!!

Don’t forget to drop your valuable feedback below !!

So in this article, we have been through How to Add Query Parameters to DART HTTP Request.

Do let us know in the comments if you are still confused about Flutter Development!!! We would love to assist you 馃檪

FlutterAgency.com聽is our portal Platform dedicated to聽Flutter Technology聽and聽Flutter Developers. The portal is full of cool resources from Flutter like聽Flutter Widget聽Guide,聽Flutter Projects,聽Code libs聽and etc.

FlutterAgency.com is one of the most popular online portals dedicated to聽Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of聽Flutter. All you need to know about Flutter Development.

Leave a Reply