+91 7002160093 / 7002484119 HOSTEL FACILITIES AVAILABLE Download App
Uncategorized

Send Flutter Data To Online Server

Admin June 28, 2025 1 views

Here's a concise and professional guide to sending data using the POST method from a Flutter screen using http package. This guide covers all major form data types used in API communication:


Step 1: Add http Dependency

Add this to your pubspec.yaml:

 dependencies: http: ^0.13.6

Step 2: Import the Library

 import 'package:http/http.dart' as http; import 'dart:convert';

Step 3: Define the Endpoint and Headers

 final String url = 'https://your-api-url.com/endpoint'; final headers = { 'Content-Type': 'application/json', // For JSON 'Authorization': 'Bearer YOUR_TOKEN', // Optional };

Form Types and POST Method Examples

1. Send JSON Data

 Future<void> sendJsonData() async { final body = jsonEncode({ 'name': 'John Doe', 'email': 'john@example.com', 'age': 30, }); final response = await http.post(Uri.parse(url), headers: headers, body: body); print(response.body); }

2. Send Form URL Encoded Data

 Future<void> sendFormUrlEncodedData() async { final body = { 'username': 'john', 'password': '123456', }; final response = await http.post( Uri.parse(url), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: body, ); print(response.body); }

3. Send Multipart/Form-Data (e.g., Image Upload)

 Future<void> sendMultipartFormData(String filePath) async { var request = http.MultipartRequest('POST', Uri.parse(url)); request.fields['user'] = 'john_doe'; request.fields['email'] = 'john@example.com'; request.files.add(await http.MultipartFile.fromPath('photo', filePath)); var response = await request.send(); print(await response.stream.bytesToString()); }

Step 4: Error Handling and Status Code Check

 if (response.statusCode == 200) { // success } else { // handle error }

Share this article: