使用Dio提交FormData时location字段存为String而非Map<String,double>的问题
解决Dio FormData中Location字段被存为String而非Map的问题
问题描述
我在使用Dio发送注册请求时,location字段的存储格式不符合预期:
- 期望后端将
location存储为Map<String, double>类型,格式如{"latitude": 1234.0, "longitude": 1234.0} - 实际后端返回的
location是String类型,值为"{\"latitude\":1234.0,\"longitude\":1234.0}"
原请求代码如下:
class RegisterRemoteDataSourceImpl extends RegisterRemoteDataSource { final Dio dio; final String username, email, password, confirmPassword; final String fullname, biography; final LocationEntity location; final File? profilePicture; RegisterRemoteDataSourceImpl({ required this.dio, required this.username, required this.email, required this.password, required this.confirmPassword, required this.fullname, required this.biography, required this.location, this.profilePicture, }); @override Future<bool> register() async { final formData = FormData.fromMap( { "username": username, "email": email, "password": password, "confirm_password": confirmPassword, "fullname": fullname, "biography": biography, "location": jsonEncode(location.toJson()), // 问题所在行 "profile_picture": profilePicture == null ? null : await MultipartFile.fromFile(profilePicture!.path), }, ); final response = await dio.post( kApiRegister, data: formData, ); if (response.statusCode == 200) { return true; } else { throw (response.statusMessage!); } } }
期望的API返回格式:
{ "token": "jfadslkjfadsljf5645456446", "user": { "id": 12, "username": "test", "email": "test@test.com", "date_joined": "2023-08-02T20:29:00.274657Z", "userprofile": { "fullname": "test", "biography": "this is test", "profile_picture": "/images/Users/user_12/IMG_20230708_171948.jpg", "location": {"latitude": 1234.0, "longitude": 1234.0} } } }
实际的API返回格式:
{ "token": "jfadslkjfadsljf5645456446", "user": { "id": 12, "username": "test", "email": "test@test.com", "date_joined": "2023-08-02T20:29:00.274657Z", "userprofile": { "fullname": "test", "biography": "this is test", "profile_picture": "/images/Users/user_12/IMG_20230708_171948.jpg", "location": "{\"latitude\":1234.0,\"longitude\":1234.0}" } } }
解决方案
问题出在你用jsonEncode()把location的Map对象转成了JSON字符串,后端收到后直接将这个字符串存储。FormData支持直接嵌套Map结构,只需去掉jsonEncode(),直接传入location.toJson()的返回值即可:
修改后的核心代码片段:
final formData = FormData.fromMap( { "username": username, "email": email, "password": password, "confirm_password": confirmPassword, "fullname": fullname, "biography": biography, "location": location.toJson(), // 直接传入Map对象 "profile_picture": profilePicture == null ? null : await MultipartFile.fromFile(profilePicture!.path), }, );
这样Dio会正确处理FormData中的嵌套Map结构,后端就能解析并存储为Map<String, double>类型,返回结果会符合预期。
内容的提问来源于stack exchange,提问作者Mohammad Mousavi
相关产品推荐
相关产品推荐

