dio Flutter 网络请求pub DioFactory 封装 get post 请求 和 请求拦截头
dio_init.dart
class DioInit {
static int timeOut = 30000; //30秒超时
static Future<Dio> init() async {
final String apiUrl = await Global.getSeverApiUrl();
final String token = await Global.getUserToken();
final Dio dio = Dio(BaseOptions(
baseUrl: apiUrl + "/",
sendTimeout: timeOut,
contentType: 'application/json',
method: "GET",
connectTimeout: timeOut,
headers: {"Access-Control-Allow-Origin": "*", 'auth': token}));
return dio;
}
static Future<Dio> initP() async {
final String apiUrl = await Global.getSeverApiUrl();
final String token = await Global.getUserToken();
final Dio dio = Dio(BaseOptions(
baseUrl: apiUrl + "/",
sendTimeout: timeOut,
contentType: 'application/json',
method: "POST",
connectTimeout: timeOut,
headers: {"Access-Control-Allow-Origin": "*", 'auth': token}));
return dio;
}
dio_factory.dart
///枚举字段
enum DioHttpType {
get,
post,
}
///dio 工厂类
class DioFactory<T extends dynamic> {
final DioHttpType dioHttpType;
final String apiUrl; // api路径
final Map<String, dynamic>? queryParameters;
final dynamic data;
DioFactory(
this.dioHttpType,
this.apiUrl, {
this.queryParameters,
this.data,
});
static DioFactory<T> get<T>(
String apiUrl, {
Map<String, dynamic>? queryParameters,
}) {
return DioFactory<T>(DioHttpType.get, apiUrl,
queryParameters: queryParameters);
}
static DioFactory<T> post<T>(
String apiUrl, {
Map<String, dynamic>? queryParameters,
dynamic data,
}) {
return DioFactory<T>(DioHttpType.post, apiUrl,
queryParameters: queryParameters, data: data);
}
Future<T?> response(
T t, {
required ResponseJsonFomratDart<T> responseJsonFomratDart,
}) async {
Dio? dio;
var r;
try {
if (dioHttpType == DioHttpType.get) {
dio = await DioInit.init();
dio.interceptors.add(InterceptorsWrapper(onError: (e, h) {
if (e.response == 503) {
MotionToast.warning(
title: Text(
'Warning',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('服务器升级中'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}));
r = await dio.get<String>(apiUrl, queryParameters: queryParameters);
} else if (dioHttpType == DioHttpType.post) {
dio = await DioInit.initP();
dio.interceptors.add(InterceptorsWrapper(onError: (e, h) {
if (e.response == 503) {
MotionToast.warning(
title: Text(
'Warning',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('服务器升级中'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}));
r = await dio.post<String>(apiUrl,
data: data, queryParameters: queryParameters);
}
if (kDebugMode) { //如果是bug 环境
log('\n✅请求状态:statusCode=${r.statusCode}, statusMessage=${r.statusMessage}\n请求方式:$dioHttpType\n请求完整apiUrl:${dio?.options.baseUrl}$apiUrl\n请求参数:$queryParameters\n返回值:$r');
}
//解析------------------
if (t is List) {
var httpResultModel =
HttpResultModel.fromJson(json.decode(r.data.toString()));
if (httpResultModel.responseStatus == 1) {
return responseJsonFomratDart(httpResultModel);
} else {
MotionToast.error(
title: Text(
'Error',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('${httpResultModel.errorMessage}'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}
if (t is Map || t == null) {
var httpResultModelTwo =
HttpResultModelTwo.fromJson(json.decode(r.data.toString()));
if (httpResultModelTwo.responseStatus == 1) {
return responseJsonFomratDart(httpResultModelTwo);
} else {
MotionToast.error(
title: Text(
'Error',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('${httpResultModelTwo.errorMessage}'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}
if (t is bool || t is String) {
var httpResultModelObj =
HttpResultModelObj.fromJson(json.decode(r.data.toString()));
if (httpResultModelObj.responseStatus == 1) {
return responseJsonFomratDart(httpResultModelObj);
} else {
MotionToast.error(
title: Text(
'Error',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('${httpResultModelObj.errorMessage}'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}
} catch (e) {
print(e.toString());
}
return null;
}
Future<T?> responseWaring(
T t, {
required ResponseJsonFomratDart<T> responseJsonFomratDart,
Function(String? str)? waring,
}) async {
Dio? dio;
var r;
try {
if (dioHttpType == DioHttpType.get) {
dio = await DioInit.init();
dio.interceptors.add(InterceptorsWrapper(onError: (e, h) {
if (e.response == 503) {
MotionToast.warning(
title: Text(
'Warning',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('服务器升级中'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}));
r = await dio.get<String>(apiUrl, queryParameters: queryParameters);
} else if (dioHttpType == DioHttpType.post) {
dio = await DioInit.initP();
dio.interceptors.add(InterceptorsWrapper(onError: (e, h) {
if (e.response == 503) {
MotionToast.warning(
title: Text(
'Warning',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('服务器升级中'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}));
r = await dio.post<String>(apiUrl,
data: data, queryParameters: queryParameters);
}
if (t is List) {
var httpResultModel =
HttpResultModel.fromJson(json.decode(r.data.toString()));
if (httpResultModel.responseStatus == 1) {
return responseJsonFomratDart(httpResultModel);
} else {
MotionToast.error(
title: Text(
'Error',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('${httpResultModel.errorMessage}'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}
if (t is Map || t == null) {
var httpResultModelTwo =
HttpResultModelTwo.fromJson(json.decode(r.data.toString()));
if (httpResultModelTwo.responseStatus == 1) {
return responseJsonFomratDart(httpResultModelTwo);
} else {
MotionToast.error(
title: Text(
'Error',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('${httpResultModelTwo.errorMessage}'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}
if (t is bool || t is String) {
var httpResultModelObj =
HttpResultModelObj.fromJson(json.decode(r.data.toString()));
if (httpResultModelObj.responseStatus == 1) {
return responseJsonFomratDart(httpResultModelObj);
} else if (httpResultModelObj.responseStatus == 9) {
var callBack = waring ?? (str) {};
callBack(httpResultModelObj.errorMessage);
} else {
MotionToast.error(
title: Text(
'Error',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
toastDuration: Duration(seconds: 2),
description: Text('${httpResultModelObj.errorMessage}'),
animationType: ANIMATION.fromTop,
position: MOTION_TOAST_POSITION.top,
width: 300,
).show(Get.context!);
}
}
} catch (e) {
print(e.toString());
}
return null;
}
}
typedef ResponseJsonFomratDart<T> = T Function(dynamic t);