Request.dart 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import 'dart:convert';
  2. import 'package:dio/dio.dart';
  3. class Response {
  4. late int code;
  5. String? message;
  6. dynamic data;
  7. Response({
  8. required this.code,
  9. this.message,
  10. this.data,
  11. });
  12. factory Response.fromJson(dynamic str) => Response.fromMap(jsonDecode(str) as Map<String, dynamic>);
  13. factory Response.fromMap(Map<String, dynamic> resp) => Response(
  14. code: resp['code'],
  15. message: resp['message'],
  16. data: resp['data'],
  17. );
  18. }
  19. Dio createRequest() {
  20. var options = BaseOptions(
  21. baseUrl: 'https://www.xx.com/api',
  22. connectTimeout: 5000,
  23. receiveTimeout: 3000,
  24. );
  25. var dio = Dio(options);
  26. dio.interceptors.add(InterceptorsWrapper(
  27. onRequest:(options, handler){
  28. // Do something before request is sent
  29. return handler.next(options); //continue
  30. // If you want to resolve the request with some custom data,
  31. // you can resolve a `Response` object eg: `handler.resolve(response)`.
  32. // If you want to reject the request with a error message,
  33. // you can reject a `DioError` object eg: `handler.reject(dioError)`
  34. },
  35. onResponse:(response,handler) {
  36. Response resp = Response.fromJson(response.data['data']);
  37. if (resp.code == 1000) {
  38. response.data = resp.data;
  39. return handler.next(response);
  40. } else {
  41. return handler.reject(response.data);
  42. }
  43. },
  44. onError: (DioError e, handler) {
  45. // Do something with response error
  46. return handler.next(e);//continue
  47. // If you want to resolve the request with some custom data,
  48. // you can resolve a `Response` object eg: `handler.resolve(response)`.
  49. }
  50. ));
  51. return dio;
  52. }
  53. var instance = createRequest();
  54. Future request (RequestOptions options) async {
  55. var resp = await instance.fetch(options);
  56. if (resp.data.runtimeType == String) {
  57. String dt = resp.data as String;
  58. dt.trim();
  59. if (dt.startsWith('{') && dt.endsWith('}')) {
  60. return jsonDecode(dt);
  61. }
  62. return dt;
  63. }
  64. return resp.data;
  65. }