flutter post request
To make a POST request in Flutter, you can use the http
package. First, make sure to add the package to your pubspec.yaml
file:
dependencies:
http: ^0.13.4
Then, import the package in your Dart file:
import 'package:http/http.dart' as http;
To send a POST request, you can use the http.post
method. Here's an example of how you can make a POST request with JSON data:
String url = 'https://api.example.com/endpoint';
Map<String, String> headers = {'Content-Type': 'application/json'};
String jsonBody = '{"key1": "value1", "key2": "value2"}';
http.Response response = await http.post(
Uri.parse(url),
headers: headers,
body: jsonBody,
);
if (response.statusCode == 200) {
// Successful request
print(response.body);
} else {
// Request failed
print('Request failed with status: ${response.statusCode}');
}
In this example, we define the URL of the endpoint we want to send the POST request to, set the Content-Type
header to application/json
, and provide the JSON body for the request. The http.post
method returns a http.Response
object, which contains the response from the server.
You can then check the statusCode
property of the response to determine if the request was successful. If the status code is 200, it means the request was successful, and you can access the response body using the body
property.
Remember to use the await
keyword before the http.post
method to wait for the response. This requires the enclosing function to be marked as async
.
That's how you can make a POST request in Flutter using the http
package. Let me know if you need any further assistance!