I am trying to send a register request to the API with Dio
, but when I use this code, the location field has a problem:
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!);
}
}
}
The result I expect when I’m checking the API :
{
"token": "jfadslkjfadsljf5645456446",
"user": {
"id": 12,
"username": "test",
"email": "[email protected]",
"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
}
}
}
Actual result in the API:
{
"token": "jfadslkjfadsljf5645456446",
"user": {
"id": 12,
"username": "test",
"email": "[email protected]",
"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
}
}
}
Unfortunately "location"
saved as String
, Its must be saved as Map<String,double>
2
Answers
If server supports
nested object
withFormData
, you can use this formTo save data as Map<String, dynamic> don’t encode it.
jsonEncode
returns String and therefore it is sent to the API as a String. Using Dio you can send any data that is "basic type" including Lists and Maps, no matter how many times they are nested in each other.