Flutter Dio封装
import 'package:dio/dio.Dart'; import 'package:path_provider/path_provider.dart'; import 'package:znw/app/net/url_co编程客栈nfig.dart'; class HttpClient { late Dio dio; static HttpClient instance = HttpClient._internal(); ///工厂构造函数与普通构造函数的区别在于, ///工厂构造函数可以自定义实例的创建过程,并根据需要返回一个新的对象或现有的对象。 factory HttpClient() { reandroidturn 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; js } } ///post请求 Future<Response?> post(String url, Map<String, dynamic>javascript;? 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 directjavascriptory = 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 简单封装demo的详细内容,更多关于Flutter Dio封装的资料请关注编程客栈(www.devze.com)其它相关文章!
精彩评论