class ConnectionUtils {
static Future<bool> isNetworkConnected() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
}
class ApiClient {
final hostName = "google.com";
final env = "DEV";
_setInstance(dio) {
dio.options.headers["Authorization"] = "";
dio.options.headers["Content-Type"] = 'application/json';
dio.options.connectTimeout = const Duration(minutes: 1).inMilliseconds;
dio.options.receiveTimeout = const Duration(minutes: 1).inMilliseconds;
if (env == "DEV") {
dio.interceptors.addAll([
PrettyDioLogger(
requestHeader: false,
requestBody: true,
responseHeader: false,
responseBody: false,
error: true,
compact: true,
)
]);
}
}
Future get(String path, {query}) async {
if (await ConnectionUtils.isNetworkConnected()) {
try {
final dio = Dio();
_setInstance(dio);
final response = await dio.get(hostName + path,
queryParameters: query,
options: Options(
followRedirects: false,
validateStatus: (status) {
return status! < 500;
},
));
return response;
} catch (e) {
if (e is DioError) {
throw Exception(e.message);
} else {
throw Exception(e.toString());
}
}
} else {
throw Exception("No Connection");
}
}
Future post(String path, dynamic data, {query}) async {
if (await ConnectionUtils.isNetworkConnected()) {
try {
final dio = Dio();
_setInstance(dio);
final response = await dio.post(
hostName + path,
data: data,
);
return response;
} catch (e) {
if (e is DioError) {
throw Exception(e.message);
} else {
throw Exception(e.toString());
}
}
} else {
throw Exception("No Connection");
}
}
Future put(String path, dynamic data, {query}) async {
if (await ConnectionUtils.isNetworkConnected()) {
try {
final dio = Dio();
_setInstance(dio);
final response =
await dio.put(hostName + path, data: data, queryParameters: query);
return response;
} catch (e) {
if (e is DioError) {
throw Exception(e.message);
} else {
throw Exception(e.toString());
}
}
} else {
throw Exception("No Connection");
}
}
Future delete(String path, {query}) async {
if (await ConnectionUtils.isNetworkConnected()) {
try {
final dio = Dio();
_setInstance(dio);
final response =
await dio.delete(hostName + path, queryParameters: query);
return response;
} catch (e) {
if (e is DioError) {
throw Exception(e.message);
} else {
throw Exception(e.toString());
}
}
} else {
throw Exception("No Connection");
}
}
}