Pubspec yaml guide package

Dio: ^1.0.0 # Request cookie path_provider: ^1.6.11 # File storeCopy the code

Request a catalogue

Defining the interface Address

class Api{
  static const String BASE_URL = 'http://xxxxxx';
  static const String LOGIN = BASE_URL + 'login/auth';
  static const String BULLETINS = BASE_URL + 'bulletins';
}
Copy the code

Initialize DIO, set related parameters, token problem class external top-level method set, will be lost. Set the token in the InterceptorsWrapper, where you can also handle the token aging problem. For example, if the request server’s current token is valid, re-create dio to request, and lock the dio object outside the class. For example, there is a scenario where the token expires and the login page is redirected.

var dio = new Dio(); Map<String, dynamic> headers = { 'content-type': 'application/json', 'accept-language': 'zh-cn', }; initOption() { dio.options .. baseUrl = Api.BASE_URL .. connectTimeout = 300000 .. headers = headers; } class DioNet { // GET static Future get(String url, [Map<String, dynamic> params]) async { Response response; BotToast.showLoading(); print('GetMothod--->$url\nparams--->$params'); Directory documentsDir = await getApplicationDocumentsDirectory(); String documentsPath = documentsDir.path; var dir = new Directory("$documentsPath/cookies"); await dir.create(); dio.interceptors .. Add (CookieManager(PersistCookieJar(dir: dir.path))) add((InterceptorsWrapper( onRequest: (Options options) async { var token = await SpUtil().getValue(SharePrefConstant.TOKEN); options.headers.addAll({'SESSION': token ?? "}); return options; }))); try { if (params ! = null) { response = await dio.get(url, queryParameters: params); } else { response = await dio.get(url); } BotToast.closeAllLoading(); return response.data; } on DioError catch (err) { BotToast.closeAllLoading(); // Handle Error httperor.dioError (err); return err; } } //POST static Future post(String url, Map<String, dynamic> params) async { BotToast.showLoading(); print('PostMethod--->$url\nparams--->$params'); Directory documentsDir = await getApplicationDocumentsDirectory(); String documentsPath = documentsDir.path; var dir = new Directory("$documentsPath/cookies"); await dir.create(); dio.interceptors .. Add (CookieManager(PersistCookieJar(dir: dir.path))) add((InterceptorsWrapper( onRequest: (Options options) async { var token = await SpUtil().getValue(SharePrefConstant.TOKEN); options.headers.addAll({'SESSION': token ?? "}); return options; }))); try { var response = await dio.post(url, data: params); BotToast.closeAllLoading(); return response.data; } on DioError catch (err) { BotToast.closeAllLoading(); // Handle Error httperor.dioError (err); return err; }}}Copy the code

Call interface, according to the status code returned by the server to do the corresponding logical processing;

Class RequestUtil {// static Future doLogin(Map<String, dynamic> params) async { var response = await DioNet.post(Api.LOGIN, params); // LoginInfo loginInfo = LoginInfo.fromJson(response); return getRespone(response); } static Future doBulletins(Map<String, dynamic> params) async {var response = await dionet. get(api.bulletins, params); return getRespone(response); Static getRespone(response) {print("response-- >$response"); try { if (isSuccess(response)) { return response; } else {switch (response['result']) {case '20011': / / jump to specify page and close the current all Routers. FinishAllToLoginPage (); BotToast.showText(text: '9999'); break; ShowText (text: response['message']); break; } } } on StackTrace catch (e) { print("e----->$e"); } } static bool isSuccess(dynamic result) { return (result ! = null && result['result'] == 'success') ? true : false; }}Copy the code

Error code message returned by DIO request

Class HttpError {/// UNKNOWN error static const String UNKNOWN = "UNKNOWN"; Static const String PARSE_ERROR = "PARSE_ERROR"; Static const String NETWORK_ERROR = "NETWORK_ERROR"; Static const String HTTP_ERROR = "HTTP_ERROR"; SSL_ERROR = "SSL_ERROR"; // certificate error static const String SSL_ERROR = "SSL_ERROR"; Static const String CONNECT_TIMEOUT = "CONNECT_TIMEOUT"; Static const String RECEIVE_TIMEOUT = "RECEIVE_TIMEOUT"; /// SEND_TIMEOUT static const String SEND_TIMEOUT = "SEND_TIMEOUT"; Static const String CANCEL = "CANCEL"; String code; String message; HttpError(this.code, this.message); HttpError.dioError(DioError error) { message = error.message; switch (error.type) { case DioErrorType.CONNECT_TIMEOUT: code = CONNECT_TIMEOUT; Message = "Network connection timed out, please check network Settings "; break; case DioErrorType.RECEIVE_TIMEOUT: code = RECEIVE_TIMEOUT; Message = "Server exception, please try again later!" ; break; case DioErrorType.SEND_TIMEOUT: code = SEND_TIMEOUT; Message = "Network connection timed out, please check network Settings "; break; case DioErrorType.RESPONSE: code = HTTP_ERROR; Message = "Server exception, please try again later!" ; break; case DioErrorType.CANCEL: code = CANCEL; Message = "Request cancelled, please request again "; break; case DioErrorType.DEFAULT: code = UNKNOWN; Message = "Network exception, please try again later!" ; break; } BotToast.showText(text: message); } @override String toString() { return 'HttpError{code: $code, message: $message}'; }}Copy the code

call

RequestUtil.doLogin(params).then((result) {
                    if (RequestUtil.isSuccess(result)) {
                    //todo somethings
                    }
Copy the code