Learn about the exploration of Flutter development, borrowed ideas from many online bigwigs, if there is any similarity, it is most likely that I copied it (manual dog head).
The purpose of this series is to record the thoughts in personal learning.
The environment and configuration used in this article
Flutter 2.2.3 DIO 4.0.0 Logger 1.1.0 #log outputCopy the code
The directory structure
Encapsulate content roughly
-
Token check
-
The log output
-
Exception handling
.
Began to encapsulate
HTTP singleton operation class: http_client.dart
I’m just saying get and POST
class HttpClient { Dio _dio; CancelToken CancelToken = CancelToken(); CancelToken CancelToken = CancelToken(); static HttpClient _instance = HttpClient._internal(); Httpclient._internal () {Map<String, dynamic> header = {}; if (null == _dio) { _dio = Dio( BaseOptions( contentType: 'application/json', connectTimeout: 10000, receiveTimeout: 10000, sendTimeout: 10000, headers: header, ), ); _dio.interceptors.add(MyHttpInterceptor()); }} static HttpClient getInstance({String baseUrl}) {if (baseUrl == null) {return _instance._normal(); } else { return _instance._otherDomain(baseUrl); HttpClient _otherDomain(String baseUrl) {if (_dio! = null) { _dio.options.baseUrl = baseUrl; } return this; } /// return the default domain name HttpClient _normal() {if (_dio! = null) { if (_dio.options.baseUrl ! = NetWorkAddress.baseUrl) { _dio.options.baseUrl = NetWorkAddress.baseUrl; } } return this; } Future<BaseResponse> get({ String url, Map<String, dynamic> params, Map<String, dynamic> data, CancelToken cancelToken, ProgressCallback onReceiveProgress, }) async { try { Response response = await _dio.get( url, queryParameters: params, cancelToken: cancelToken ?? this.cancelToken, onReceiveProgress: onReceiveProgress, ); return handleResponse(response, cancelToken: cancelToken ?? this.cancelToken); } on Exception catch (e) { return handleException(e, cancelToken: cancelToken ?? this.cancelToken); } } Future<BaseResponse> post({ String url, Map<String, dynamic> params, Map<String, dynamic> data, CancelToken cancelToken, ProgressCallback onReceiveProgress, }) async { try { Response response = await _dio.post( url, queryParameters: params, cancelToken: cancelToken ?? this.cancelToken, onReceiveProgress: onReceiveProgress, ); return handleResponse(response, cancelToken: cancelToken ?? this.cancelToken); } on Exception catch (e) { return handleException(e, cancelToken: cancelToken ?? this.cancelToken); }}}Copy the code
Custom interceptor: http_interceptor.dart
Here only log output, no other processing
class MyHttpInterceptor extends InterceptorsWrapper { @override void onRequest(RequestOptions options, RequestInterceptorHandler handler) { super.onRequest(options, handler); Logger. I (" -- -- -- -- -- -- -- -- -- -- a request -- -- -- -- -- -- -- -- -- \ nurl: ${options. Uri. The toString ()} \ n "" headers: ${options. The headers} \ nmethod: ${options.method}\nparams: ${options.queryParameters}\n" "data: ${options.data}"); } @override void onResponse(Response response, ResponseInterceptorHandler handler) { super.onResponse(response, handler); Var json = jsonEncode(response.data); var json = jsonEncode(response.data); Logger. I (" -- -- -- -- -- -- -- -- -- -- return -- -- -- -- -- -- -- -- -- \ nurl: ${response. RequestOptions. Uri} \ n "" code: ${response. StatusCode} \ nmessage: ${response.statusMessage}\ndata: $json"); } @override void onError(DioError err, ErrorInterceptorHandler handler) { super.onError(err, handler); Logger. E (" -- -- -- -- -- -- -- -- -- -- wrong -- -- -- -- -- -- -- -- -- \ ntype: ${err. Type} \ nmessage: ${err. Message} "); }}Copy the code
Return result handling: http_response.dart
BaseResponse handleResponse(Response Response, {CancelToken CancelToken,}) {response.statuscode! = 200) return handleException( HttpException(response.statusMessage, response.statusCode), cancelToken: cancelToken, ); return BaseResponse( code: response.statusCode, message: response.statusMessage, data: response.data, ); } BaseResponse handleException(Exception Exception, {CancelToken CancelToken,}) {HttpException _parseException; if (exception is HttpException) _parseException = exception; else _parseException = parseException(exception); / / here exception handling logger. Can be e (" -- -- -- -- -- -- -- -- -- -- the exception handling -- -- -- -- -- -- -- -- -- \ n ${_parseException. ToString ()} "); return BaseResponse(code: _parseException.code, message: _parseException.message); } HttpException parseException(Exception Exception) {if (Exception is DioError) {switch (exception.type) { Case DioErrorType. ConnectTimeout: return HttpException (" connection timeout, please try again "); Case DioErrorType. SendTimeout: return HttpException (" request timeout, please try again later "); Case DioErrorType. ReceiveTimeout: return HttpException (" request failed, please try again later "); Case DioerrorType. cancel: // Request canceled return HttpException(exception.message); case DioErrorType.response: try { int code = exception.response? .statusCode; Switch (code) {case 401: return HttpException(" login invalid ", code); case 500: return HttpException(exception.response? .statusMessage, 500); case 400: default: return HttpException(exception.response? .statusMessage, code); } } on Exception catch (_) { return HttpException(exception.response.statusMessage); } return HttpException(exception.response.statusMessage); Return HttpException(exception.message, exception.hashcode); } } else { return HttpException(exception.toString()); }}Copy the code
Data type returned: response_model.dart
class BaseResponse<T>{ int code; String message; T data; BaseResponse({this.code,this.message,this.data}); @override String toString() { return "code: $code\nmessage: $message\ndata: $data"; }}Copy the code
Dart extension: http_exception.dart
class HttpException implements Exception{
final String _message;
String get message => _message ?? this.runtimeType.toString();
final int _code;
int get code => _code ?? -1;
HttpException([this._message, this._code]);
String toString() {
return "code: $code\nmessage: $message";
}
}
Copy the code
use
var response = HttpClient.getInstance().get(url: NetWorkAddress.userInfo,);
Copy the code
This is the end of encapsulation.
The last
When I was writing this article, I still looked up many dio package articles written by my predecessors, and gained a lot. This article is really a minor one, and it is purely a record of personal learning (because I often read it and forget it…). , what write wrong place, big guys please forgive me ~