FlutterDio亲妈级别封装教程
前不久看到 ⼤佬的dio封装,经过摸索,改吧改吧,使⽤的不错。对于之前 ⼤佬⽂章中⼀些已经失效的做了修正
为什么⼀定要封装⼀⼿?
token拦截,错误拦截,统⼀错误处理,统⼀缓存,信息封装(错误,正确)
Cookie滚犊⼦
不管cookie,再见
全局初始化,传⼊参数
dio初始化,传⼊baseUrl, connectTimeout, receiveTimeout,options,header 等。dio初始化的时候允许我们传⼊的⼀些配置
dio初始化的配置
这⾥说下,之前 ⼤佬的帖⼦中的options,最新版的dio已经使⽤requestOptions, 之前的merge,现在使⽤
copyWith。详情向下看
如果要⽩嫖完整的⽅案
可以参考使⽤这套⽅案开发的 flutter + getx 仿开眼视频app,有star的⼤佬可以赏点star。
项⽬地址
提取码:ts8q
提取码:c6mc
初始化
这⾥说下,可以在初始化的时候传⼊,也可以⼿写传⼊,例如我这⾥定义了四个,第⼀个
⽤于全局request时候给请求投加上context-type:json。第⼆个是全局错误处理,下⾯的内容会介绍部分。
cache,全局处理接⼝缓存数据,retry重试(我暂时没怎么⽤)
class Http {
static final Http _instance = Http._internal();
// 单例模式使⽤Http类,
factory Http() => _instance;
static late final Dio dio;
CancelToken _cancelToken = new CancelToken();
Http._internal() {
// BaseOptions、Options、RequestOptions 都可以配置参数,优先级别依次递增,且可以根据优先级别覆盖参数
BaseOptions options = new BaseOptions();
dio = Dio(options);
// 添加request
dio.interceptors.add(RequestInterceptor());
// 添加error
dio.interceptors.add(ErrorInterceptor());
// // 添加cache
dio.interceptors.add(NetCacheInterceptor());
// // 添加retry
dio.interceptors.add(
RetryOnConnectionChangeInterceptor(
requestRetrier: DioConnectivityRequestRetrier(
dio: dio,
connectivity: Connectivity(),
),
),
);
// 在调试模式下需要抓包调试,所以我们使⽤代理,并禁⽤HTTPS证书校验
// if (PROXY_ENABLE) {
//  (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
//      (client) {
//    client.findProxy = (uri) {
/
/      return "PROXY $PROXY_IP:$PROXY_PORT";
//    };
//    //代理⼯具会提供⼀个抓包的⾃签名证书,会通不过证书校验,所以我们禁⽤证书校验
//    client.badCertificateCallback =
//        (X509Certificate cert, String host, int port) => true;
//  };
// }
}
///初始化公共属性
///
/// [baseUrl] 地址前缀
/
// [connectTimeout] 连接超时赶时间
/// [receiveTimeout] 接收超时赶时间
/// [interceptors] 基础
void init({
String? baseUrl,
int connectTimeout = 1500,
int receiveTimeout = 1500,
Map<String, String>? headers,
List<Interceptor>? interceptors,
List<Interceptor>? interceptors,
}) {
dio.options = pyWith(
baseUrl: baseUrl,
connectTimeout: connectTimeout,
receiveTimeout: receiveTimeout,
headers: headers ?? const {},
);
// 在初始化http类的时候,可以传⼊
if (interceptors != null && interceptors.isNotEmpty) {
dio.interceptors..addAll(interceptors);
}
}
/
/ 关闭dio
void cancelRequests({required CancelToken token}) {
_cancelToken.cancel("cancelled");
}
// 添加认证
// 读取本地配置
Map<String, dynamic>? getAuthorizationHeader() {
Map<String, dynamic>? headers;
// 从getx或者sputils中获取
// String accessToken = Global.accessToken;
String accessToken = "";
if (accessToken != null) {
headers = {
'Authorization': 'Bearer $accessToken',
};
}
return headers;
}
Future get(
String path, {
Map<String, dynamic>? params,
Options? options,
CancelToken? cancelToken,
bool refresh = false,
bool noCache = !CACHE_ENABLE,
String? cacheKey,
bool cacheDisk = false,
}) async {
Options requestOptions = options ?? Options();
requestOptions = pyWith(
extra: {
"refresh": refresh,
"noCache": noCache,
"cacheKey": cacheKey,
"cacheDisk": cacheDisk,
},
);
Map<String, dynamic>? _authorization = getAuthorizationHeader();
if (_authorization != null) {
requestOptions = pyWith(headers: _authorization);        }
Response response;
response = (
path,
queryParameters: params,
options: requestOptions,
cancelToken: cancelToken ?? _cancelToken,
);
return response.data;
return response.data;
}
Future post(
String path, {
Map<String, dynamic>? params,
data,
Options? options,
CancelToken? cancelToken,
}) async {
Options requestOptions = options ?? Options();
Map<String, dynamic>? _authorization = getAuthorizationHeader();
if (_authorization != null) {
requestOptions = pyWith(headers: _authorization);        }
var response = await dio.post(
path,
data: data,
queryParameters: params,
options: requestOptions,
cancelToken: cancelToken ?? _cancelToken,
);
return response.data;
}
Future put(
String path, {
data,
Map<String, dynamic>? params,
Options? options,
CancelToken? cancelToken,
}) async {
Options requestOptions = options ?? Options();
Map<String, dynamic>? _authorization = getAuthorizationHeader();
if (_authorization != null) {
requestOptions = pyWith(headers: _authorization);        }
var response = await dio.put(
path,
data: data,
queryParameters: params,
options: requestOptions,
cancelToken: cancelToken ?? _cancelToken,
);
return response.data;
}
Future patch(
String path, {
data,
Map<String, dynamic>? params,
Options? options,
CancelToken? cancelToken,
}) async {
Options requestOptions = options ?? Options();
Map<String, dynamic>? _authorization = getAuthorizationHeader();
if (_authorization != null) {
requestOptions = pyWith(headers: _authorization);        }
var response = await dio.patch(
path,
data: data,
queryParameters: params,
options: requestOptions,
cancelToken: cancelToken ?? _cancelToken,
cancelToken: cancelToken ?? _cancelToken,
);
return response.data;
}
Future delete(
String path, {
data,
Map<String, dynamic>? params,
Options? options,
CancelToken? cancelToken,
}) async {
Options requestOptions = options ?? Options();
Map<String, dynamic>? _authorization = getAuthorizationHeader();
if (_authorization != null) {
requestOptions = pyWith(headers: _authorization);        }
flutter开发app
var response = await dio.delete(
path,
data: data,
queryParameters: params,
options: requestOptions,
cancelToken: cancelToken ?? _cancelToken,
);
return response.data;
}
}
dio
下⾯我们来看下,下⾯是⼀个处理处理案例

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。