What is HTTP in Flutter?
Most modern apps need to communicate with a backend server over the internet. HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. In Flutter, you can make HTTP requests using the http package, which provides a simple, async API for GET, POST, PUT, DELETE, and more. This tutorial will guide you through making API calls, handling responses, and displaying data in your Flutter app.
Adding the http Package
First, add the http package to your pubspec.yaml dependencies:
dependencies:
http: ^1.2.0
Then run flutter pub get to install it.
Making a GET Request
The simplest HTTP request is a GET. It retrieves data from a server. You use http.get() with a Uri and get a Future<Response> back.
The response object contains the status code (200 means success), headers, and body. The body is a raw string; you'll usually parse it as JSON.
Parsing JSON Responses
Most APIs return JSON. Use dart:convert to decode the string into a Dart object (Map or List).
Making a POST Request
To send data to a server, use POST. You provide a body (usually a JSON string) and set the Content-Type header to application/json.
PUT, PATCH, DELETE
Handling Errors Gracefully
Always handle network errors and HTTP errors. Use try/catch for exceptions (like no internet) and check status codes for HTTP errors.
Displaying Data with FutureBuilder
In Flutter, you often combine HTTP requests with FutureBuilder to manage the asynchronous state and rebuild the UI when data arrives.
Common Mistakes
- Not checking
mountedwhen callingsetStateafter an async operation: useif (mounted)to avoid memory leaks.
- Not checking
- Creating the
Futureinsidebuild: This causes the future to restart on every rebuild. Store it ininitStateor as a variable.
- Creating the
- Ignoring
statusCode: Always check the status code; a 200 does not guarantee success (e.g., 404 might return a page).
- Ignoring
- Forgetting to set
Content-Typeheader for POST: The server may not understand the body format.
- Forgetting to set
- Not handling exceptions: Network calls can fail; always wrap in try/catch.
Best Practices
- Use a separate service class for API calls to keep your UI clean.
- Define models for your data (like
Postclass) to use type‑safe objects.
- Define models for your data (like
- Use
FutureBuilderfor one‑time loads, and considerStreamBuilderfor real‑time updates.
- Use
- Show loading indicators while waiting for data.
- Handle offline scenarios gracefully (e.g., show a cached version or a friendly error).
Complete Example
Key Takeaways
- Use the
httppackage to make network requests in Flutter.
- Use the
- GET retrieves data; POST sends data; PUT/PATCH update; DELETE removes.
- Always check
response.statusCodeto handle HTTP errors.
- Always check
- Parse JSON with
jsonDecodefromdart:convert.
- Parse JSON with
- Display async data with
FutureBuilderfor a reactive UI.
- Display async data with
- Store the future outside
buildto avoid repeated requests.
- Store the future outside