How to post data to API in flutter
In mobile application development, sometimes it is necessary to post data from mobile application to the server side for processing, storage or retrieval. This could include user input from forms, device sensor data, or any other information specific to your app. This data can be in various formats, like JSON, XML or form-encoded data. In this tutorial we will learn how to post data to API in flutter.
POST data in Flutter
To post data to an API in Flutter, we will use the http package, which provides functions to make HTTP requests like GET, POST, PUT, DELETE etc. Here’s an example of how to post data to a server using Flutter http package.
1- Add the http package to your project by adding the following line to your pubspec.yaml file:
dependencies:
http: ^0.13.3
2- Run ‘flutter pub get’ command in terminal
3- Import the http package in your Dart file:
import 'package:http/http.dart' as http;
4- Create a function to handle the HTTP POST request.
Future<void> postData() async {
// The URL where you want to post the data
final url = Uri.parse('https://example.com/post');
// The data you want to send
final data = {'name': 'John Doe', 'email': 'john@example.com'};
try {
final response = await http.post(
url,
body: data,
);
if (response.statusCode == 200) {
// Request successful, do something with the response
print('Data posted successfully');
print(response.body);
} else {
// Request failed, handle the error
print('Failed to post data: ${response.statusCode}');
}
} catch (e) {
// An error occurred, handle the exception
print('Error: $e');
}
}
5- Call the postData() function when you want to post the data to the server:
postData();
These were the simple steps to post or send data to API in flutter. Make sure to replace the url with actual url where you want to post your data. Depending on your API’s requirements, you may need to modify the headers, authentication, or handle response data differently.
We can also get data from api in flutter using http package.
In the example above, we’re using jsonEncode from the dart:convert library to convert the data object into a JSON-encoded string. We also set the Content-Type header to ‘application/json’ to indicate that we’re sending JSON data in the request body.
The response from the API can be accessed through the response object. We can check the statusCode to determine if the request was successful (usually 200 for a successful request) or handle any error conditions accordingly.
Remember to handle exceptions that may occur during the HTTP request, such as network errors or timeouts.
Conclusion
In this tutorial we have seen that sending data to server is how much easy in flutter. Hope this example will help you in your ongoing projects.