I have to make a Post Api Request using Flutter. The Postman screenshot is attached for reference. can someone help me with the code [1]: https://i.sstatic.net/VQ23OMth.png
Here is the code sample that I have tried
class ProfileRemoteDatasourceImpl implements ProfileRemoteDatasource {
@override
Future<SaveBuyerModel> saveBuyerInfo(
{required File image, required BuyerModel buyerModel}) async {
try {
final body = {"File": image, "buyerModel": buyerModel};
const endpoint = '${MyAppConstants.baseUrl}/v1/save/buyer';
var myurl = Uri.parse(endpoint);
final response = await http.post(myurl,
headers: {
'Content-Type': 'application/json',
},
body: body);
Map<String, dynamic> data1 = json.decode(response.body)["data"];
return SaveBuyerModel.fromMap(data1);
} on ServerException catch (e) {
throw ServerException(e.message);
} catch (e) {
throw TimeoutException(e.toString());
}
}
}
According to your screenshot:
multipart/form-data
So your request will look like:
var bytes = await image.readAsBytes();
var request = http.MultipartRequest('POST', uri)
..headers.addAll({'Content-Type': 'multipart/form-data'})
..files.add(await http.MultipartFile.fromBytes('File', bytes))
..files.add(await http.MultipartFile.fromString(
'buyerModel',
buyerModel.toJson(),
filename: 'input.json',
contentType: MediaType('application', 'json')
)
);
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
return SaveBuyerModel.fromMap(jsonDecode(response.body)["data"]);