我尝试用Dio
向API发送注册请求,但是当我使用这个代码时,location字段出现了问题:
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() /* {"latitude": 1234.0, "longitude": 1234.0}) */,
"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",
// this is true
"location": {"latitude": 1234.0, "longitude": 1234.0}
// this is true
}
}
}
型
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",
// this is my problem
"location": "{\"latitude\":1234.0,\"longitude\":1234.0}"
// this is my problem
}
}
}
型
不幸的是,"location"
保存为String
,它必须保存为Map<String,double>
2条答案
按热度按时间nhhxz33t1#
如果服务器支持
nested object
和FormData
,则可以使用此表单字符串
0ejtzxu12#
要将数据保存为Map<String,dynamic>,请不要对其进行编码。
jsonEncode
返回String,因此它作为String发送给API。使用Dio,你可以发送任何“基本类型”的数据,包括列表和Map,不管它们彼此嵌套多少次。