Flutter中POST请求如何正确发送含数组的JSON请求体?
问题原因
你直接把jsonMap传给http.post的body参数时,Flutter的http库会默认把数据编码成application/x-www-form-urlencoded(表单格式),这种格式无法正确传递数组类型的数据,服务器自然解析不了你的goals列表。而Postman里你是直接发送JSON格式的请求体,所以能正常工作。
解决方法
要发送JSON格式的请求体,需要两步:
- 用
json.encode()把你的Map转换成JSON字符串 - 设置请求头的
Content-Type为application/json,明确告诉服务器接收的是JSON数据
修改后的代码如下:
import 'dart:convert'; // 必须导入这个包才能使用json.encode // 确保programGoals是List<String>类型 List<String> programGoals = ["goal1", "goal2", "goal3"]; Map<String, dynamic> jsonMap = { "title": itemTitle, "description": itemDescription, "category": category, "imageCover": "", "author": "", "authorImageProfile": "", "dayCount": "10", "goals": programGoals }; final response = await http.post( Uri.parse('$localHost$url'), headers: {'Content-Type': 'application/json'}, // 新增请求头 encoding: Encoding.getByName('utf-8'), body: json.encode(jsonMap), // 将Map转为JSON字符串 );
额外注意
- 务必导入
dart:convert包,否则json.encode会报错 - 确认
programGoals是List<String>类型,避免因类型不匹配导致JSON编码失败
内容的提问来源于stack exchange,提问作者Sam Nolan
相关产品推荐
相关产品推荐

