Flutter Dio 网络框架的二次封装

dio 二次封装

功能点

1、支持get、post、put、delete 四种请求方式

2、支持文件上传并获取上传进度

3、支持最大重试请求次数

4、支持通过传递 解析方法,对数据进行解析,出现异常并捕获异常

所使用到的插件如下:

  # HTTP 请求
  dio: ^5.4.0
  cookie_jar: ^4.0.8
  dio_cookie_manager: ^3.1.1

创建dio请求类 net_work_http_task.dart

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:flutter/foundation.dart';

// 请求类型
enum HttpMethod {
  get,
  post,
  put,
  delete,
}

// HTTP 请求base类
class NetWorkHttpTask {
  // 重写构造方法
  NetWorkHttpTask({
    required this.path,
    this.httpMethod = HttpMethod.post,
    this.timeOut = 30000,
    this.timeOutMax = 0,
  });

  // 请求类型
  HttpMethod httpMethod;

  // 最大超时请求次数
  int timeOutMax;

  // 超时时间
  int timeOut;

  // ip
  String ip = "Https://192.168.1.1";

  // 端口号
  int port = 8080;

  // 请求链接
  String path;

  // 请求参数
  Map<String, dynamic> queryParameters = {};

  // 配置共同参数
  void configParam() {}

  // 请求返回内容
  Response? response;

  // 请求异常
  Exception? exception;

  /// 请求基础配置
  late var baseOptions = BaseOptions(
      baseUrl: "$ip:$port",
      connectTimeout: Duration(seconds: timeOut),
      receiveTimeout: Duration(seconds: timeOut),
      responseType: ResponseType.json,
      contentType: "multipart/form-data; boundary=",
      headers: {"X-Access-Token": ""});

  /// 全局共同Dio
  var shareDio = (BaseOptions baseOptions) {
    Dio dio = Dio(baseOptions);
    var cookieJar = CookieJar();
    dio.interceptors.add(CookieManager(cookieJar));
    //简单粗暴方式处理校验证书方法
    (dio.httpClientAdapter as IOHttpClientAdapter).onHttpClientCreate =
        (client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) {
        return true;
      };
      return null;
    };
    return dio;
  };

  // 获取文件上传进度
  Function(int progress, int total)? fileUploadProgress;

  /// 文件上传
  Future<Response?> fileUploadRequest(FormData formData) async {
    Dio dio = shareDio(baseOptions);
    try {
      response = await dio.post(path, data: formData,
          onSendProgress: (int progress, int total) {
        if (fileUploadProgress != null) {
          fileUploadProgress!(progress, total);
        }
      });
      if (response == null || response?.data == null) {
        return null;
      } else {
        return response?.data;
      }
    } catch (exception) {
      this.exception = exception as Exception?;
      _requestExceptionHandling();
      return null;
    }
  }

  /// 开始请求
  Future<Response?> httpRequest() async {
    Dio dio = shareDio(baseOptions);
    try {
      response = _requestRetry(dio) as Response?;
      if (response == null || response?.data == null) {
        return null;
      } else {
        return response?.data;
      }
    } catch (exception) {
      this.exception = exception as Exception?;
      _requestExceptionHandling();
      return null;
    }
  }

  /// 设置最大请求及请求次数
  Future<Response?> _requestRetry(Dio dio) async {
    for (int i = 0; i <= timeOutMax; i++) {
      try {
        return await _dioRequest(dio);
      } on DioException catch (error) {
        if (error.type == DioExceptionType.connectionTimeout ||
            error.type == DioExceptionType.sendTimeout ||
            error.type == DioExceptionType.receiveTimeout) {
          if (i <= timeOutMax) {
            continue;
          }
        }
        rethrow;
      }
    }
    return null;
  }

  /// 请求类型
  Future<Response?> _dioRequest(Dio dio) async {
    Response? response;
    switch (httpMethod) {
      case HttpMethod.post:
        if (queryParameters.isEmpty) {
          response = await dio.post(path);
        } else {
          response = await dio.post(path, queryParameters: queryParameters);
        }
        break;
      case HttpMethod.get:
        if (queryParameters.isEmpty) {
          response = await dio.get(path);
        } else {
          response = await dio.get(path, queryParameters: queryParameters);
        }
        break;
      case HttpMethod.put:
      case HttpMethod.delete:
        assert(false, "put delete暂不支持");
        break;
    }
    return response;
  }

  /// 获取请求成功状态
  bool requestStatus() {
    return response != null && response?.statusCode == 200;
  }

  /// 请求异常处理
  void _requestExceptionHandling() {
    if (kDebugMode) {
      print(exception.toString());
    }
  }

  /// 解析数据
  Future<T?> parseData<T>(T? Function(Map<String, dynamic> json) function) async {
    final normalResult = await httpRequest();
    try {
      return normalResult == null ? null : function(normalResult);
    } catch (e) {
      if (kDebugMode) {
        print(e.toString());
      }
      return null;
    }
  }
}

到此完成了dio的网络框架的二次封装。

下面写一个测试例子

创建一个Model类 home_model.dart


// To parse this JSON data, do
//
//     final homeModel = homeModelFromJson(jsonString);

import 'dart:convert';

HomeModel homeModelFromJson(String str) => HomeModel.fromJson(json.decode(str));

String homeModelToJson(HomeModel data) => json.encode(data.toJson());

class HomeModel {
  String? greeting;
  List<String>? instructions;

  HomeModel({
    this.greeting,
    this.instructions,
  });

  factory HomeModel.fromJson(Map<String, dynamic> json) => HomeModel(
    greeting: json["greeting"],
    instructions: json["instructions"] == null ? [] : List<String>.from(json["instructions"]!.map((x) => x)),
  );

  Map<String, dynamic> toJson() => {
    "greeting": greeting,
    "instructions": instructions == null ? [] : List<dynamic>.from(instructions!.map((x) => x)),
  };
}

请求类和模型类创建完成后,下面就是使用了

    NetWorkHttpTask task = NetWorkHttpTask(path: "api/home");
    task.parseData(HomeModel.fromJson).then((value) {
      print(value);
    });

到此就完成了使用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在使用 Flutter Dio 进行网络请求时,可以将其进行封装,以便于代码的复用和维护。以下是一个简单的 Flutter Dio 封装示例: ```dart import 'package:dio/dio.dart'; class HttpUtil { static HttpUtil instance; Dio dio; BaseOptions options; // 构造函数 HttpUtil() { options = BaseOptions( baseUrl: 'https://api.example.com/', // 接口地址 connectTimeout: 5000, // 连接超时时间 receiveTimeout: 3000, // 接收超时时间 headers: { 'Content-Type': 'application/json', // 设置请求头 }, ); dio = Dio(options); } // 单例模式 static HttpUtil getInstance() { if (instance == null) { instance = HttpUtil(); } return instance; } // GET 请求 Future<Map<String, dynamic>> get(String url, {Map<String, dynamic> params}) async { Response response; try { response = await dio.get(url, queryParameters: params); } on DioError catch (e) { return Future.error(e); } return response.data; } // POST 请求 Future<Map<String, dynamic>> post(String url, {Map<String, dynamic> params}) async { Response response; try { response = await dio.post(url, data: params); } on DioError catch (e) { return Future.error(e); } return response.data; } } ``` 在上述示例中,我们定义了一个 HttpUtil 类,其中包含了 Dio 实例的初始化、GET 和 POST 请求的封装。我们可以通过 `HttpUtil.getInstance()` 获取 HttpUtil 的单例对象,然后通过调用 `get` 或 `post` 方法来发起网络请求。这样做的好处是可以将网络请求的相关设置和配置统一管理,方便后续的维护和扩展。同时,通过封装,也避免了在多个地方重复编写相同的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王 哪跑!!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值