flutter⽹络请求封装直接上代码吧,拿⾛不谢!
import 'dart:convert';
import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter_application_yiguan/utils/jq_utils.dart';
import 'package:fluttertoast/fluttertoast.dart';
/**
* json在线⽣成model⼯具
* caijinglong.github.io/json2dart/index_ch.html
* 运⾏以下命令:
* flutter packages pub run build_runner build
* flutter packages pub run build_runner watch
*/
/// 请求完成回调⽅法
typedef CompleteCallback = void Function(DioError? error, dynamic result);
const String kNoConnectivityCode = '3001';
/// brief: 请求⽅式枚举值
/// 注意:Dart语⾔的枚举不⽀持指定原始值
enum JQHttpType { get, post }
class JQBaseHttpRequest {
/// JQHttpType type 请求⽅式
/// String url      请求地址
/
// Map<String, String> httpHeader
/// Map params      请求参数
/// CompleteCallback completeCallback 请求完成回调
static httpRequest({
required String url,
required JQHttpType type,
Map<String, dynamic>? httpHeader,
Map<String, dynamic>? params,
CompleteCallback? completeCallback,
}) async {
JQUtils.printf('url-->$url');
JQUtils.printf('params-->$params');
/// 设置 Options
Options option = Options();
/// 请求⽅式
/// 设置 headers
Map<String, dynamic> headers = new Map();
if (httpHeader != null) {
headers.addAll(httpHeader);
}
option.headers = headers;
JQUtils.printf('option.headers---------->${option.headers}');
/// 超时时间 15000毫秒ms(15秒)
/// 发送超时
option.sendTimeout = 15000;
/// 接收超时
var connectivityResult = await (new Connectivity().checkConnectivity());
if (connectivityResult == ) {
/// 没有⽹络
RequestOptions requestOptions = RequestOptions(path: url);
Response response = Response(
data: {'status': kNoConnectivityCode, 'message': '当前⽹络不可⽤,请检查⽹络是否正常'},
requestOptions: requestOptions,
requestOptions: requestOptions,
statusCode: 3001,
statusMessage: '当前⽹络不可⽤,请检查⽹络是否正常',
);
DioError error = DioError(
response: response,
requestOptions: RequestOptions(path: url),
type: her,
error: Error.safeToString('当前⽹络不可⽤,请检查⽹络是否正常'),      );
completeCallback!(error, null);
/// 实际上返回的是response的data数据
return response.data;
} else {
/// 有⽹络
Dio dio = new Dio();
try {
Response response = quest(url,
// data: params,
queryParameters: params,
options: option);
JQUtils.printf('⽹络请求成功');
JQUtils.printf('-----------response----------');
/// 打印headers
JQUtils.printf('response.headers ------>');
JQUtils.printf(response.headers);
/// response是⼀个JSON对象
JQUtils.printf('-----------data----------');
/// 打印data
JQUtils.printf('response.data ------>');
JQUtils.printf('json格式 == ' + de(response.data));
if (completeCallback != null) {
completeCallback(null, response.data);
}
/// 实际上返回的是response的data数据
return response.data;
} on DioError catch (e) {
/// 请求异常处理
/// 延时0.3秒执⾏返回,处理和loading的重合
Future.delayed(Duration(milliseconds: 300), () {
/// error存在,底层封装统⼀显⽰提⽰
Fluttertoast.showToast(
msg: "⽹络请求异常",
gravity: ToastGravity.CENTER,
);
JQUtils.printf('延时0.3s执⾏');
});
JQUtils.printf('⽹络请求异常======');
JQUtils.printf(e);
JQUtils.printf('e.response====');
flutter pubJQUtils.sponse);
JQUtils.printf('e.response.data');
JQUtils.sponse?.data);
if (completeCallback != null) {
completeCallback(e, null);
}
/// 实际上返回的是response的data数据
sponse?.data;
}
}
}
/// ⽂件下载
static httpDownload({
required String url,
required String localSavePath,
required JQHttpType type,
required JQHttpType type,
Map<String, dynamic>? httpHeader,
Map<String, dynamic>? params,
CancelToken? cancelToken,
ProgressCallback? progressCallback,
CompleteCallback? completeCallback,
}) async {
JQUtils.printf('url-->$url');
JQUtils.printf('params-->$params');
/// 设置 Options
Options option = Options();
/// 请求⽅式
/// 设置 headers
Map<String, dynamic> headers = new Map();
if (httpHeader != null) {
headers.addAll(httpHeader);
}
option.headers = headers;
JQUtils.printf('option.headers---------->${option.headers}');
JQUtils.printf('params---------->${params}');
/
// 超时时间 15000毫秒ms(15秒)
/// 发送超时
option.sendTimeout = 15000;
/// 接收超时
var connectivityResult = await (new Connectivity().checkConnectivity());
if (connectivityResult == ) {
/// 没有⽹络
RequestOptions requestOptions = RequestOptions(path: url);
Response response = Response(
data: {'status': kNoConnectivityCode, 'message': '当前⽹络不可⽤,请检查⽹络是否正常'},        requestOptions: requestOptions,
statusCode: 3001,
statusMessage: '当前⽹络不可⽤,请检查⽹络是否正常',
);
DioError error = DioError(
response: response,
requestOptions: RequestOptions(path: url),
type: her,
error: Error.safeToString('当前⽹络不可⽤,请检查⽹络是否正常'),
);
completeCallback!(error, null);
/// 实际上返回的是response的data数据
return response;
} else {
/// 有⽹络
Dio dio = new Dio();
try {
Response response = await dio.download(url, localSavePath,
queryParameters: params,
options: option,
onReceiveProgress: progressCallback == null
null
: (int count, int total) {
if (total == -1) {
/// 不知道进度的默认50%
total = count * 2;
}
progressCallback(count, total);
},
cancelToken: cancelToken);
JQUtils.printf('⽹络请求成功');

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