Fri, Dec 9, 2022
Read in 2 minutes
In this post we learn how to make a post request using http package in flutter.
Alright, let’s take a look at a detailed explanation on how to make an HTTP POST request in Flutter using the http
package.
Add the http
package to your pubspec.yaml
file:
dependencies:
http: ^0.13.4
You can use a newer version of the package if available.
Import the http
package and dart:convert
library in the file where you want to make the HTTP POST request:
import 'package:http/http.dart' as http;
import 'dart:convert';
Define the URL endpoint to which you want to send the POST request:
String url = 'https://example.com/api/user';
Define the data you want to send in the request body. This can be in a Map
or List
format:
Map<String, dynamic> data = {
'name': 'John Doe',
'email': 'johndoe@example.com',
};
Convert the data to JSON format using the json.encode()
method from the dart:convert
library:
String jsonData = json.encode(data);
Send the HTTP POST request using the http.post()
method:
http.post(Uri.parse(url), body: jsonData).then((response) {
if (response.statusCode == 200) {
// Success!
} else {
// Handle errors
}
}).catchError((error) {
// Handle errors
});
The http.post()
method takes in two arguments: the URL endpoint to send the request to, and the request body data. In this case, we’re passing in the JSON data we created earlier as the request body.
The then()
method is used to handle the response from the server. We check the status code of the response to determine if the request was successful or not. If the status code is 200, we assume the request was successful.
The catchError()
method is used to handle any errors that may occur during the request.
And that’s it! This is a basic example of how to make an HTTP POST request in Flutter using the http
package. You can modify the code to suit your specific use case, such as adding headers to the request or handling different types of responses.