network<T> method
Networking class to handle API requests
Use the request
callback to call an API
handleSuccess
overrides the response on a successful status code
handleFailure
overrides the response on a failure
Usage: Future<List
Implementation
Future<T?> network<T>(
{required Function(Dio api) request,
Function(Response response)? handleSuccess,
Function(DioException error)? handleFailure,
String? bearerToken,
String? baseUrl,
bool useUndefinedResponse = true,
Map<String, dynamic> headers = const {}}) async {
try {
Map<String, dynamic> oldHeader = _api.options.headers;
Map<String, dynamic> newValuesToAddToHeader = {};
if (headers.isNotEmpty) {
for (var header in headers.entries) {
if (!oldHeader.containsKey(header.key)) {
newValuesToAddToHeader.addAll({header.key: header.value});
}
}
}
if (bearerToken != null) {
newValuesToAddToHeader.addAll({"Authorization": "Bearer $bearerToken"});
}
_api.options.headers.addAll(newValuesToAddToHeader);
String oldBaseUrl = _api.options.baseUrl;
if (baseUrl != null) {
_api.options.baseUrl = baseUrl;
}
Response response = await request(_api);
_api.options.headers = oldHeader; // reset headers
_api.options.baseUrl = oldBaseUrl; // reset base url
_api.options.queryParameters = {}; // reset query parameters
dynamic data = handleResponse<T>(response, handleSuccess: handleSuccess);
if (data != T && useUndefinedResponse) {
onUndefinedResponse(data, response, _context);
}
_context = null;
return data;
} on DioException catch (dioError) {
NyLogger.error(dioError.toString());
onError(dioError);
if (_context != null) {
displayError(dioError, _context!);
}
if (handleFailure != null) {
return handleFailure(dioError);
}
return null;
} on Exception catch (e) {
NyLogger.error(e.toString());
return null;
}
}