You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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).

1. Implementing an HTTP GET Request in Flutter

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 finally block to close the HTTP client
  • Enhanced error messages for easier debugging
  • Used HttpStatus.ok for 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');
  }
}

2. Implementing an HTTP POST Request in Flutter (and Troubleshooting)

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.get instead of postUrl/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 await and handling the future properly (e.g., using FutureBuilder in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:20:08