'Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Response'
I am trying to get the JSON response from a server
Future<dynamic> post(String path,
{Map<String, dynamic>? params, String? token}) async {
http.Response responseJson;
try {
var response = await http.post(
getPath(path, null),
body: json.encode(params),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
},
);
log(response.body);
responseJson = _returnResponse(response);
} on SocketException {
throw const FormatException();
}
return responseJson;
}
//returnResponse
dynamic _returnResponse(http.Response response) {
switch (response.statusCode) {
case 200:
case 201:
var responseJson = json.decode(response.body.toString());
return responseJson;
case 400:
throw BadRequestException();
case 401:
case 403:
throw UnauthorisedException();
case 404:
throw NotFound();
case 422:
throw UnprocessableEntity();
case 500:
throw InternalServerError();
default:
throw FetchDataException();
}
}
But anytime I make the request, the request returns 200 successful but I get an Unhandled exception as below
E/flutter ( 8302): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Response'
E/flutter ( 8302): #0 ApiClient.post
package:app/const/api_helper.dart:39
I have search through other simpler question, but nothing fixes my issue
this is the json format I am expecting
{
"_id":"675676",
"role":"user",
"status":"active",
"interest":[
"Business"
],
"name":"xyz",
"email":"[email protected]",
"phoneNumber":"123456677",
"location":"Somewhere",
"createdAt":"2020-04-18T08:16:23.976Z",
"updatedAt":"2022-05-14T23:13:49.195Z",
"__v":0,
"id":"675676"
}
Can anyone help me figure out what's wrong?
Solution 1:[1]
responseJson is being declared as type http.Response. You can omit that entirely and just return the response from your method.
Future<dynamic> post(String path,
{Map<String, dynamic>? params, String? token}) async {
try {
var response = await http.post(
getPath(path, null),
body: json.encode(params),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
},
);
log(response.body);
return _returnResponse(response);
} on SocketException {
throw const FormatException();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dan Harms |
