import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:znw/app/net/url_config.dart';
class HttpClient {
late Dio dio;
static HttpClient instance = HttpClient._internal();
///工厂构造函数与普通构造函数的区别在于,
///工厂构造函数可以自定义实例的创建过程,并根据需要返回一个新的对象或现有的对象。
factory HttpClient() {
return instance;
}
HttpClient._internal() {
print('构造函数。。。。。。。。。。。。。。');
dio = Dio();
dio.options.baseUrl = UrlConfig.BASE_URL;
dio.options.connectTimeout = 8000;
dio.interceptors.add(LogInterceptor(responseBody: true)); // 输出响应内容体
}
/// get请求
Future<Response?> get(String url, {Map<String, dynamic>? map}) async {
try {
var result = await dio.get(url, queryParameters: map);
return result;
} catch (e) {
print('HttManager get e $e }');
return null;
}
}
///post请求
Future<Response?> post(String url, Map<String, dynamic>? map) async {
try {
var result = await dio.post(url, queryParameters: map);
return result;
} catch (e) {
print('HttManager post e $e }');
return null;
}
}
///上传文件 fileName 文件名字 fileDir 文件路径 formData 自定义参数
Future<Response?> uploadFile(String url, String? fileName, String fileDir,
Map<String, dynamic> formData) async {
try {
formData['file'] =
await MultipartFile.fromFile(fileDir, filename: fileName);
var response = await dio.post(url, data: formData);
print(response.data);
return response;
} catch (e) {
return null;
}
}
///下载文件 downLoadPath下载路径,
///fileName 下载之后生成的文件名字,
///onProgress 下载进度
///onFinish 下载完成
downLoad(
String downLoadPath,
String fileName,
Function(int count, int total) onProgress,
Function(String path) onFinish,
Function(DioError e) onError) async {
final directory = await getExternalStorageDirectory();
String localPath = directory!.path;
String savePath = "$localPath/$fileName";
String apkUrl = downLoadPath;
///参数一 文件的网络储存URL
///参数二 下载的本地目录文件
///参数三 下载监听
try {
await dio.download(apkUrl, savePath,
onReceiveProgress: (received, total) {
if (total != -1) {
///当前下载的百分比例
print("${(received / total * 100).toStringAsFixed(0)}%");
onProgress(received, total);
}
});
onFinish(savePath);
print(savePath);
} on DioError catch (e) {
// 异常处理代码
onError(e);
}
}
}
Flutter Dio 简单封装
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...