When working with HTTP requests in Dart, you can use the http package to send network requests. When adding query parameters to requests, you can either manually construct the URL or use the Uri class to generate a URL with query parameters more conveniently. The following outlines the steps and examples for adding query parameters to a GET request using the Uri class:
Step 1: Add the http package dependency
First, ensure that your Dart project includes the http package dependency. You can add the following dependency to your pubspec.yaml file:
yamldependencies: http: ^0.13.3
Then run pub get to install the dependency.
Step 2: Import the http package
In your Dart file, import the http package:
dartimport 'package:http/http.dart' as http;
Step 3: Construct a URL with query parameters using the Uri class
You can use the Uri class to construct a URL with query parameters. This avoids manually concatenating strings and reduces the risk of errors.
dartvar uri = Uri.https('www.example.com', '/search', {'query': 'dart', 'page': '1'});
Here, Uri.https takes the first parameter as the domain, the second as the path, and the third as a Map representing the query parameters.
Step 4: Send the HTTP request
Use the constructed uri to send the HTTP request:
dartvar response = await http.get(uri); if (response.statusCode == 200) { print('Response body: ${response.body}'); } else { print('Request failed with status: ${response.statusCode}.'); }
In this example, we send a GET request to www.example.com/search with the query parameters query=dart and page=1. Then, we check the response status code and print the response content or error message.
Complete Example:
The following is a complete example demonstrating how to construct a request with query parameters and send it:
dartimport 'package:http/http.dart' as http; void main() async { var uri = Uri.https('www.example.com', '/search', {'query': 'dart', 'page': '1'}); var response = await http.get(uri); if (response.statusCode == 200) { print('Response body: ${response.body}'); } else { print('Request failed with status: ${response.statusCode}.'); } }
Using the Uri class helps manage URLs and their query parameters more safely and conveniently, especially when dealing with multiple parameters or requiring URL encoding. This approach avoids errors that could arise from manually concatenating strings.