Request.dart 2.5KB

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