dio_helper.dart 1.9 KB

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