Introduction to HTTP in Dart
Making HTTP requests is a common task for any application that communicates with web services. Dart provides the http package, which is a simple, easy‑to‑use library for sending HTTP requests. It supports GET, POST, PUT, DELETE, and other methods, and handles both synchronous and asynchronous operations. This guide will teach you how to use the http package effectively.
First, add the package to your pubspec.yaml:
dependencies:
http: ^1.2.0
Then run dart pub get to install it.
Basic GET Request
The http.get() function sends a GET request to a URL. It returns a Future<Response>. The response contains status code, headers, and body.
GET with Headers
You can add custom headers by passing a headers map.
POST Request
To send data with POST, pass a body (usually a map encoded to JSON or form data).
PUT and DELETE
Handling JSON Response
Most APIs return JSON. Use jsonDecode from dart:convert to parse the response body.
Error Handling
Always handle network errors and HTTP errors gracefully. Use try/catch and check status codes.
Using a Client for Multiple Requests
If you need to make multiple requests to the same host, use a Client to reuse a connection and benefit from keep‑alive.
Timeout
You can set a timeout on requests to avoid waiting indefinitely.
Key Takeaways
- Add the
httppackage to your dependencies.
- Add the
- Use
http.get(),http.post(), etc., to send requests.
- Use
- Always convert URIs with
Uri.parse().
- Always convert URIs with
- Check
response.statusCodeto handle errors.
- Check
- Use
jsonDecodeto parse JSON responses.
- Use
- For multiple requests, use a
Clientfor efficiency.
- For multiple requests, use a
- Set timeouts to prevent hanging.