Reputation: 47
Here I am trying to send the Object Map in the multipart request but my request is going as a string, i need send the Object Map not String . but request .fields wants a String from me.
"barberAddress":{
"State":"test",
"City":"test",
"Street": "test",
"location":{
"lat":1.2,
"lang":2.1
}
},
This is my post method
postFormDataBarber({
@required String endPoint,
File picB,barberName,BarberAddress barberAddress, }) async {
var url = Uri.parse('${BaseUrl.baseUrl}$endPoint');
var request = http.MultipartRequest("POST", url);
request.fields["barberAddress"] = json.encode(barberAddress);// {"State":"aaa","City":"vvv","Street":"eeee","location":{"lat":null,"lang":null}}
request.files.add(picB);
final data = await request.send();
return data;
}
This is my model and I want to add this model map object to the Mango database
class BarberAddress {
BarberAddress({
@required this.state,
@required this.city,
@required this.street,
this.location,
});
String state;
String city;
String street;
BarberLocation location;
factory BarberAddress.fromJson(Map<String, dynamic> json) =>
BarberAddress(
state: json["State"],
city: json["City"],
street: json["Street"],
location: BarberLocation.fromJson(json["location"]),
);
class BarberLocation {
BarberLocation({
@required this.lat,
@required this.lang,
});
double lat;
double lang;
factory BarberLocation.fromJson(Map<String, dynamic> json) =>
BarberLocation(
lat: json["lat"].toDouble(),
lang: json["lang"].toDouble(),
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lang": lang,
};
}
Upvotes: 2
Views: 2642
Reputation: 585
Flutter multipart request fields take only Map<String, String>. If you pass Map<String, dynamic> will arise error.
You need to encode your Map<String,dynamic> then covert to string.
if your server can decode this string you can apply my solution
THE SOLUTION FOR ME:
var data = {
"State":"test",
"City":"test",
"Street": "test",
"location":{
"lat":1.2,
"lang":2.1
}
};
var header = {
"Content-Type": 'multipart/form-data',
"Accept": 'application/json'
};
Map<String, String> obj = {"barberAddress": json.encode(data).toString()};
var request = http.MultipartRequest("POST", Uri.parse("url here"))
..fields.addAll(obj)
..headers.addAll(header)
..files.addAll(files);
var streamResponse = await request.send();
var response = await http.Response.fromStream(streamResponse);
// Your result here
IN SEVER SIDE
LARAVEL:
$obj = json_decode($request["barberAddress"], true);
// Your code here
OR
$obj = json_decode($request->barberAddress, true);
// Your code here
IF IT IS HARD TO DECODE YOUR OBJECT ON SEVER USE
flutter dio package through this link : dio flutter package
I THINK MAY HELP SOMEONE
Upvotes: 2