call static method
Implementation
static Future call(String method, String url,
{dynamic body,
Function? fromJson,
String? rootPath,
bool? list,
dynamic bearer = "",
Map<String, String>? headers}) async {
var req = http.Request(method, Uri.parse(url));
var dh = await defaultHeaders(bearer: bearer);
if (headers != null) {
dh.addAll(headers);
}
req.headers.addAll(dh);
if (body != null) {
if (body is String) {
req.body = body;
} else {
var x = jsonEncode(body);
// print("ENCODED");
// print(x);
req.body = x;
}
}
http.Response response;
try {
var streamedResponse = await req.send();
response = await http.Response.fromStream(streamedResponse);
} catch (err) {
// probably bad connection or something
throw "Error connecting to API: $err";
}
if (response.statusCode == 404) {
throw NotFound();
}
var jsonmap;
try {
jsonmap = json.decode(response.body);
} catch (err) {
print("ERROR decoding json: $err");
// if (response.statusCode != 200) {
throw "${response.statusCode} ${response.body}";
// }
// throw err;
}
if (debug) print('jsonmap: ' + response.body);
if (response.statusCode != 200) {
// resp.error = ErrorResponse.fromJson(jsonmap['error']);
// return resp;
throw jsonmap['error']['message'];
}
// If the server did return a 200 OK response, then parse the JSON.
if (rootPath != null && rootPath != "") {
jsonmap = jsonmap[rootPath];
}
if (fromJson != null) {
if (list ?? false) {
return List.from(jsonmap.map((model) => fromJson(model)));
}
// print("about to fromJson");
return fromJson(jsonmap);
}
return jsonmap;
}