1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- import 'dart:convert';
-
- import 'package:dio/dio.dart';
- import 'package:flutter/foundation.dart';
- import 'package:get/get.dart';
-
- class Response {
- late int code;
- String? message;
- dynamic data;
-
- Response({
- required this.code,
- this.message,
- this.data,
- });
-
- factory Response.fromJson(dynamic str) =>
- Response.fromMap(jsonDecode(str) as Map<String, dynamic>);
-
- factory Response.fromMap(Map<String, dynamic> resp) => Response(
- code: resp['code'],
- message: resp['message'],
- data: resp['data'],
- );
- }
-
- final client = GetPlatform.isAndroid ? 'android' : 'ios';
-
- Dio createRequest() {
- var options = BaseOptions(
- baseUrl: 'https://machine.njyunzhi.com/api/' + client + '/farmer',
- connectTimeout: 5000,
- receiveTimeout: 3000,
- );
-
- var dio = Dio(options);
- dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
- // Do something before request is sent
- return handler.next(options); //continue
- // If you want to resolve the request with some custom data,
- // you can resolve a `Response` object eg: `handler.resolve(response)`.
- // If you want to reject the request with a error message,
- // you can reject a `DioError` object eg: `handler.reject(dioError)`
- }, onResponse: (response, handler) {
- var resp = response.data as Map<String, dynamic>;
- if (resp['code'] == 1000) {
- response.data = resp['data'];
- return handler.next(response);
- } else {
- return handler.reject(response.data);
- }
- }, onError: (DioError e, handler) {
- // Do something with response error
- return handler.next(e); //continue
- // If you want to resolve the request with some custom data,
- // you can resolve a `Response` object eg: `handler.resolve(response)`.
- }));
-
- return dio;
- }
-
- var instance = createRequest();
-
- Future request(String path,
- {data,
- Map<String, dynamic>? queryParameters,
- CancelToken? cancelToken,
- Options? options,
- ProgressCallback? onSendProgress,
- ProgressCallback? onReceiveProgress}) async {
-
- var resp = await instance.request(path,
- data: data,
- queryParameters: queryParameters,
- cancelToken: cancelToken,
- options: options);
-
- if (resp.data.runtimeType == String) {
- String dt = resp.data as String;
- dt.trim();
- if (dt.startsWith('{') && dt.endsWith('}')) {
- return jsonDecode(dt);
- }
- return dt;
- }
-
- return resp.data;
- }
|