Flutter Dio 简单封装demo

Flutter Dio封装 import package:dio dio dart ; import package:path_provider path

 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封装的资料请关注好代码网其它相关文章!

您可能有感兴趣的文章
Flutter入门学习Dart语言变量及基本如何使用概念

Flutter 异步编程之单线程下异步模型图文示例详解

如何如何使用Flutter开发一款电影APP详解

Flutter进阶之如何实现动画效果(二)

Flutter定义tabbar底部导航路由跳转的方法