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

In this blog post, we’ll explore how to add query parameters to a Dart HTTP request. This is a common task when working with web APIs and other online services.

The Need for Query Parameters

Query parameters are used to pass additional data in the URL of an HTTP request. They’re often used to filter or sort data, but can also be used to pass any kind of data that needs to be included with a request.

In Dart, we use the `http` package to make HTTP requests. However, adding query parameters is not as straightforward as one might expect.

Constructing a Uri

To add query parameters to an HTTP request in Dart, we need to construct a . This may seem like a complex task, but it’s actually quite simple once you understand the process.

We start by defining a map of query parameters:

final queryParameters = {
  'param1': 'one',
  'param2': 'two',
};

Next, we use this map to construct a . We do this using the Uri.https constructor:

final uri =
    Uri.https('www.myurl.com', '/api/v1/test', queryParameters);

This will create a

Using Uri.parse and replace

Alternatively, we can use the Uri.parse method to parse an existing URL string and then add query parameters using the replace method:

final uri = Uri.parse('$baseUrl/v1/endpoint').replace(
  queryParameters: {
    'page': page,
    'itemsPerPage': itemsPerPage,
  },
);

This will create a new

Putting it all Together

To complete our HTTP request, we’ll use the constructed

final response = await http.get(uri, headers: {
  HttpHeaders.authorizationHeader: 'Token $token',
  HttpHeaders.contentTypeHeader: 'application/json',
});

Conclusion

Adding query parameters to an HTTP request in Dart is a straightforward process that can be achieved using the Uri. By constructing a