Dio get client => _client!;
/// 创建 dio 实例对象
HttpManager._internal() {
if (_client == null) {
/// 全局属性:请求前缀、连接超时时间、响应超时时间
BaseOptions options = BaseOptions(
connectTimeout: CONNECT_TIMEOUT,
receiveTimeout: RECEIVE_TIMEOUT,
);
_client = Dio(options);
}
}
///初始化公共属性
/// [baseUrl] 地址前缀
/// [connectTimeout] 连接超时赶时间
/// [receiveTimeout] 接收超时赶时间
/// [interceptors] 基础拦截器
void init(
{String? baseUrl,
int? connectTimeout,
int? receiveTimeout,
List? interceptors}) {
_client!.options = _client!.options.copyWith(
baseUrl: baseUrl,
connectTimeout: connectTimeout,
receiveTimeout: receiveTimeout,
);
if (interceptors != null && interceptors.isNotEmpty) {
_client!.interceptors…addAll(interceptors);
}
}
///Get网络请求
///[url] 网络请求地址不包含域名
///[params] url请求参数支持restful
///[options] 请求配置
///[successCallback] 请求成功回调
///[errorCallback] 请求失败回调
///[tag] 请求统一标识,用于取消网络请求
get({
String? url,
Map<String, dynamic>? params,
Options? options,
HttpSuccessCallback? successCallback,
HttpFailureCallback? errorCallback,
String? tag,
}) async {
return _request(
url: url,
params: params,
method: GET,
options: options,
successCallback: successCallback!,
errorCallback: errorCallback!,
tag: tag!,
);
}
///post网络请求
///[url] 网络请求地址不包含域名
///[data] post 请求参数
///[params] url请求参数支持restful
///[options] 请求配置
///[successCallback] 请求成功回调
///[errorCallback] 请求失败回调
///[tag] 请求统一标识,用于取消网络请求
post({
String? url,
data,
Map<String, dynamic>? params,
Options? options,
HttpSuccessCallback? successCallback,
HttpFailureCallback? errorCallback,
@required String? tag,
}) async {
return _request(
url: url!,
data: data,
method: POST,
params: params!,
options: options!,
successCallback: successCallback!,
errorCallback: errorCallback!,
tag: tag!,
);
}
///统一网络请求
///[url] 网络请求地址不包含域名
///[data] post 请求参数
///[params] url请求参数支持restful
///[options] 请求配置
///[successCallback] 请求成功回调
///[errorCallback] 请求失败回调
///[tag] 请求统一标识,用于取消网络请求
_request({
String? url,
String? method,
data,
Map<String, dynamic>? params,
Options? options,
HttpSuccessCallback? successCallback,
HttpFailureCallback? errorCallback,
@required String? tag,
}) async {
//检查网络是否连接
ConnectivityResult connectivityResult =
await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
if (errorCallback != null) {
errorCallback(HttpError(HttpError.NETWORK_ERROR, “网络异常,请稍后重试!”));
}
return;
}
//设置默认值
params = params ?? {};
method = method ?? ‘GET’;
options?.method = method;
options = options ??
Options(
method: method,
)