Flutter Dio 简单封装demo

 更新时间:2023年07月27日 10:39:36   作者:大虾啊啊啊  
这篇文章主要为大家介绍了Flutter Dio简单封装示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

 Flutter Dio封装

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 简单封装demo的详细内容,更多关于Flutter Dio封装的资料请关注脚本之家其它相关文章!

相关文章

最新评论