如何在Flutter中实现AJAX GET请求及POST请求?附代码求助
Hey there! Let's break down how to handle HTTP GET and POST requests in Flutter (note: we usually refer to these as HTTP requests rather than AJAX in Flutter, since AJAX is more browser-focused, but the core idea is the same).
You can use either the low-level HttpClient class (like your sample code) or the more convenient http package (recommended for most use cases). Let's cover both approaches:
Using HttpClient (polishing your existing code)
Your initial code is a solid start, but it has a few gaps for robustness. Here's an improved version:
import 'dart:convert'; import 'dart:io'; Future<List<dynamic>> fetchUsers() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/users'); final httpClient = HttpClient(); try { final request = await httpClient.getUrl(url); final response = await request.close(); if (response.statusCode == HttpStatus.ok) { final jsonString = await response.transform(utf8.decoder).join(); return json.decode(jsonString); } else { throw Exception('Failed to load users: Status code ${response.statusCode}'); } } catch (e) { throw Exception('Error fetching users: $e'); } finally { httpClient.close(); // Critical to avoid resource leaks! } }
Key improvements:
- Added a clear return type (
Future<List<dynamic>>) instead of a local result variable - Added a
finallyblock to close the HTTP client - Enhanced error messages for easier debugging
- Used
HttpStatus.okfor better readability over numeric codes
Using the http package (simpler approach)
First, add the dependency to your pubspec.yaml:
dependencies: http: ^1.1.0
Then implement the GET request with minimal boilerplate:
import 'package:http/http.dart' as http; import 'dart:convert'; Future<List<dynamic>> fetchUsers() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users')); if (response.statusCode == 200) { return json.decode(response.body); } else { throw Exception('Failed to load users'); } }
First, note that the code you shared is for a GET request, not POST. Let's build a proper POST implementation, then go over common pitfalls you might hit:
Using HttpClient for POST
import 'dart:convert'; import 'dart:io'; Future<dynamic> createUser(Map<String, dynamic> userData) async { final url = Uri.parse('https://jsonplaceholder.typicode.com/users'); final httpClient = HttpClient(); try { final request = await httpClient.postUrl(url); // Set header to tell server we're sending JSON request.headers.set('Content-Type', 'application/json; charset=utf-8'); // Encode your data to JSON and add to the request request.write(json.encode(userData)); final response = await request.close(); if (response.statusCode == HttpStatus.created) { final jsonString = await response.transform(utf8.decoder).join(); return json.decode(jsonString); } else { throw Exception('Failed to create user: Status code ${response.statusCode}'); } } catch (e) { throw Exception('Error creating user: $e'); } finally { httpClient.close(); } }
Using the http package for POST
import 'package:http/http.dart' as http; import 'dart:convert'; Future<dynamic> createUser(Map<String, dynamic> userData) async { final response = await http.post( Uri.parse('https://jsonplaceholder.typicode.com/users'), headers: {'Content-Type': 'application/json; charset=utf-8'}, body: json.encode(userData), ); if (response.statusCode == 201) { return json.decode(response.body); } else { throw Exception('Failed to create user'); } }
Common POST Request Issues to Check
Since you mentioned trying to implement POST but shared GET code, here are the most likely problems you might be facing:
- Wrong request method: Accidentally using
getUrl/http.getinstead ofpostUrl/http.post - Missing content-type header: If sending JSON, you must set
Content-Type: application/json—otherwise the server won't parse your data correctly - Unencoded data: Forgetting to run
json.encode()on your Dart map will send raw string data the server can't interpret - Poor async handling: Make sure you're calling the POST function with
awaitand handling the future properly (e.g., usingFutureBuilderin your UI) - Mismatched request body: Double-check that your data matches the server's expected format (required fields, correct data types)
内容的提问来源于stack exchange,提问作者Vineeth Vijayan

