dio_helper.dart 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import 'package:dio/dio.dart';
  2. import 'constats.dart';
  3. class DioHelper{
  4. static late Dio dio;
  5. static init()
  6. {
  7. dio = Dio(
  8. BaseOptions(
  9. receiveDataWhenStatusError: true,
  10. connectTimeout: 30*1000, // 30 seconds
  11. receiveTimeout: 30*1000 // 30 seconds
  12. ),
  13. );
  14. }
  15. static Future<Response> getData({required String endPoint,Map<String, dynamic>? query,
  16. required String baseUrl}) async
  17. {
  18. dio.options.baseUrl = baseUrl;
  19. dio.options.headers =
  20. {
  21. 'Content-Type':'application/json',
  22. 'Accept': 'application/json',
  23. };
  24. try {
  25. return await dio.get(endPoint,queryParameters: query,);
  26. } on DioError catch (ex) {
  27. if (ex.type == DioErrorType.connectTimeout) {
  28. throw Exception("Connection Timeout Exception");
  29. }
  30. if (ex.type == DioErrorType.receiveTimeout) {
  31. throw Exception("Receive Timeout Exception");
  32. }
  33. throw Exception(ex.message);
  34. }
  35. }
  36. static Future<Response> postData({
  37. required String endPoint,
  38. Map<String, dynamic>? query,
  39. required Map<String, dynamic> data,
  40. bool isRow = true,
  41. bool isPut = false,
  42. String lang = 'en',
  43. String? token,
  44. required String baseUrl,
  45. }) async
  46. {
  47. dio.options.followRedirects = true;
  48. dio.options.validateStatus = (status) => true;
  49. dio.options.baseUrl = baseUrl;
  50. dio.options.headers = {
  51. 'Content-Type':'application/json',
  52. 'Accept': 'application/json',
  53. 'Authorization':'key= $fcmKey',
  54. };
  55. return !isPut ? await dio.post(
  56. endPoint,
  57. queryParameters: query,
  58. data: isRow ? data : FormData.fromMap(data),
  59. ) : await dio.put(
  60. endPoint,
  61. queryParameters: query,
  62. data: isRow ? data : FormData.fromMap(data),
  63. );
  64. }
  65. }