fetching the response from API and dealing with the errors / converting Bytestreem to Map in flutter
610
Add this As for Error your statusCode is not 200
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
await response.stream.bytesToString().then((value) {
print(value);
var jsonResponse = json.decode(response.body.toString());
var nameError = jsonResponse["errors"]["name"][0];
var emailError = jsonResponse["errors"]["email"][0];
var usernameError = jsonResponse["errors"]["username"][0];
var passwordError = jsonResponse["errors"]["password"][0];
//now can print any print(emailError);
});
}
Comments
-
M.Nasri over 1 year
I am trying to communicate with a PHP backend using API but I can not reach the body of the response.
I got the base code from the postman. And here is the data of the body response:
I need to reach the message, and the errors to show them in the UI, the problem is
response.stream
it's type is Bytestreem and I can not convert it to MapMy code:
Future<void> _authenticateUp(String email, String password, String passwordconfirmation, String username, String name, {String phonenumber}) async { var headers = { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }; var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register')); request.fields.addAll({ 'email': email, 'password': password, 'password_confirmation': passwordconfirmation, 'username': username, 'name': name, 'phone_number': phonenumber }); request.headers.addAll(headers); http.StreamedResponse response = await request.send(); try { if (response.statusCode == 200) { await response.stream.bytesToString().then((value) { print(value); }); } else { // here I want to print the message and the errors } } catch (e) { throw e; } }
-
Tasnuva Tavasum oshin about 3 yearsdo you want to read the response?
-
M.Nasri about 3 yearsNot just reading. I want to get the message and the errors and store them in variamles to show them in the UI
-
-
M.Nasri about 3 yearsI want also to decode this Map {"message":"The given data was invalid.","errors":{"email":["The email has already been taken."]}} to use the values
-
Tasnuva Tavasum oshin about 3 yearsok i have updated the answer kindly have a look