dioPost function
Perform a POST or PUT request
Implementation
Future<DIO.Response<dynamic>?> dioPost({
bool? isPost = true,
dynamic data,
String? endUrl,
bool? sendFile = false,
String? loginRouteName,
}) async {
var dio = DIO.Dio();
// Configure Dio to allow insecure connections
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(client) {
client.badCertificateCallback =
(X509Certificate cert, String host, int port) {
// Allow insecure connections
return true;
};
return client;
};
final storage = GetStorage();
if (storage.read(USER_LOGIN) ?? false) {
dio.options.headers['Authorization'] =
"Bearer ${storage.read(USER_TOKEN) ?? ''}";
}
if (sendFile ?? false) {
dio.options.headers["Content-Type"] = "multipart/form-data";
}
try {
DIO.Response<dynamic> response;
if (isPost ?? true) {
response = await dio.post(
"$BASE_URL$endUrl",
data: data,
options: DIO.Options(
validateStatus: (status) => true,
sendTimeout: const Duration(milliseconds: 100000),
receiveTimeout: const Duration(milliseconds: 100000),
),
);
} else {
response = await dio.put(
"$BASE_URL$endUrl",
data: data,
options: DIO.Options(
validateStatus: (status) => true,
sendTimeout: const Duration(milliseconds: 100000),
receiveTimeout: const Duration(milliseconds: 100000),
),
);
}
_handleStoreStatus(response);
if (!response.data["error"] && _shouldNavigateToLogin(response)) {
await _clearUserData();
if (loginRouteName != null && Get.isRegistered<GetDelegate>()) {
Get.offAllNamed(loginRouteName);
}
return null;
}
if (isDebugMode.value) {
log("\n\n${isPost ?? true ? 'POST:' : 'PUT'} $BASE_URL$endUrl\nSTATUS CODE: ${response.statusCode}\n${jsonEncode(response.data)}\n\n");
}
return response;
} catch (e) {
// Handle exceptions
if (isDebugMode.value) {
log("Error in ${isPost ?? true ? 'POST' : 'PUT'} request: $e");
}
return null;
}
}