Flutter学习

flutter网络请求封装-callBack形式

2021-08-23  本文已影响0人  蒲公英少年

直接上代码吧,拿走不谢!

import 'dart:convert';
import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter_application_yiguan/utils/jq_utils.dart';
import 'package:fluttertoast/fluttertoast.dart';

/**
 * json在线生成model工具
 * https://caijinglong.github.io/json2dart/index_ch.html
 * 运行以下命令:
 * flutter packages pub run build_runner build
 * flutter packages pub run build_runner watch
 */

/// 请求完成回调方法
typedef CompleteCallback = void Function(DioError? error, dynamic result);

const String kNoConnectivityCode = '3001';

/// brief: 请求方式 枚举值
/// 注意:Dart语言的枚举不支持指定原始值
enum JQHttpType { get, post }

class JQBaseHttpRequest {
  /// JQHttpType type 请求方式
  /// String url      请求地址
  /// Map<String, String> httpHeader
  /// Map params      请求参数
  /// CompleteCallback completeCallback 请求完成回调
  static httpRequest({
    required String url,
    required JQHttpType type,
    Map<String, dynamic>? httpHeader,
    Map<String, dynamic>? params,
    CompleteCallback? completeCallback,
  }) async {
    JQUtils.printf('url-->$url');
    JQUtils.printf('params-->$params');

    /// 设置 Options
    Options option = Options();

    /// 请求方式
    option.method = (type != JQHttpType.post) ? 'GET' : 'POST';

    /// 设置 headers
    Map<String, dynamic> headers = new Map();
    if (httpHeader != null) {
      headers.addAll(httpHeader);
    }
    option.headers = headers;
    JQUtils.printf('option.headers---------->${option.headers}');

    /// 超时时间 15000毫秒ms(15秒)
    /// 发送超时
    option.sendTimeout = 15000;

    /// 接收超时
    option.receiveTimeout = 15000;

    var connectivityResult = await (new Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      /// 没有网络
      RequestOptions requestOptions = RequestOptions(path: url);
      Response response = Response(
        data: {'status': kNoConnectivityCode, 'message': '当前网络不可用,请检查网络是否正常'},
        requestOptions: requestOptions,
        statusCode: 3001,
        statusMessage: '当前网络不可用,请检查网络是否正常',
      );
      DioError error = DioError(
        response: response,
        requestOptions: RequestOptions(path: url),
        type: DioErrorType.other,
        error: Error.safeToString('当前网络不可用,请检查网络是否正常'),
      );
      completeCallback!(error, null);

      /// 实际上返回的是response的data数据
      return response.data;
    } else {
      /// 有网络
      Dio dio = new Dio();
      try {
        Response response = await dio.request(url,
            // data: params,
            queryParameters: params,
            options: option);
        JQUtils.printf('网络请求成功');
        JQUtils.printf('-----------response----------');

        /// 打印headers
        JQUtils.printf('response.headers ------>');
        JQUtils.printf(response.headers);

        /// response是一个JSON对象
        JQUtils.printf('-----------data----------');

        /// 打印data
        JQUtils.printf('response.data ------>');
        JQUtils.printf('json格式 == ' + json.encode(response.data));

        if (completeCallback != null) {
          completeCallback(null, response.data);
        }

        /// 实际上返回的是response的data数据
        return response.data;
      } on DioError catch (e) {
        /// 请求异常处理
        /// 延时0.3秒执行返回,处理和loading的重合
        Future.delayed(Duration(milliseconds: 300), () {
          /// error存在,底层封装统一显示提示
          Fluttertoast.showToast(
            msg: "网络请求异常",
            gravity: ToastGravity.CENTER,
          );
          JQUtils.printf('延时0.3s执行');
        });
        JQUtils.printf('网络请求异常======');
        JQUtils.printf(e);
        JQUtils.printf('e.response====');
        JQUtils.printf(e.response);
        JQUtils.printf('e.response.data');
        JQUtils.printf(e.response?.data);
        if (completeCallback != null) {
          completeCallback(e, null);
        }

        /// 实际上返回的是response的data数据
        return e.response?.data;
      }
    }
  }

  /// 文件下载
  static httpDownload({
    required String url,
    required String localSavePath,
    required JQHttpType type,
    Map<String, dynamic>? httpHeader,
    Map<String, dynamic>? params,
    CancelToken? cancelToken,
    ProgressCallback? progressCallback,
    CompleteCallback? completeCallback,
  }) async {
    JQUtils.printf('url-->$url');
    JQUtils.printf('params-->$params');

    /// 设置 Options
    Options option = Options();

    /// 请求方式
    option.method = (type != JQHttpType.post) ? 'GET' : 'POST';

    /// 设置 headers
    Map<String, dynamic> headers = new Map();
    if (httpHeader != null) {
      headers.addAll(httpHeader);
    }
    option.headers = headers;
    JQUtils.printf('option.headers---------->${option.headers}');
    JQUtils.printf('params---------->${params}');

    /// 超时时间 15000毫秒ms(15秒)

    /// 发送超时
    option.sendTimeout = 15000;

    /// 接收超时
    option.receiveTimeout = 15000;

    var connectivityResult = await (new Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      /// 没有网络
      RequestOptions requestOptions = RequestOptions(path: url);
      Response response = Response(
        data: {'status': kNoConnectivityCode, 'message': '当前网络不可用,请检查网络是否正常'},
        requestOptions: requestOptions,
        statusCode: 3001,
        statusMessage: '当前网络不可用,请检查网络是否正常',
      );
      DioError error = DioError(
        response: response,
        requestOptions: RequestOptions(path: url),
        type: DioErrorType.other,
        error: Error.safeToString('当前网络不可用,请检查网络是否正常'),
      );
      completeCallback!(error, null);

      /// 实际上返回的是response的data数据
      return response;
    } else {
      /// 有网络
      Dio dio = new Dio();
      try {
        Response response = await dio.download(url, localSavePath,
            queryParameters: params,
            options: option,
            onReceiveProgress: progressCallback == null
                ? null
                : (int count, int total) {
                    if (total == -1) {
                      /// 不知道进度的默认50%
                      total = count * 2;
                    }
                    progressCallback(count, total);
                  },
            cancelToken: cancelToken);
        response.extra = <String, dynamic>{"localPath": localSavePath};

        JQUtils.printf('网络请求成功');
        JQUtils.printf('-----------response----------');

        /// 打印headers
        JQUtils.printf('response.headers ------>');
        JQUtils.printf(response.headers);

        /// response是一个JSON对象
        JQUtils.printf('-----------data----------');

        /// 打印data
        JQUtils.printf('response.data ------>');
        JQUtils.printf(response.data);
        JQUtils.printf('localSavePath = ' + localSavePath);

        if (completeCallback != null) {
          // 下载文件这里,把文件的本地存储地址返回
          completeCallback(null, localSavePath);
        }

        /// 实际上返回的是response的data数据
        return response;
      } on DioError catch (e) {
        /// 请求异常处理
        /// 延时0.3秒执行返回,处理和loading的重合
        Future.delayed(Duration(milliseconds: 300), () {
          /// error存在,底层封装统一显示提示
          Fluttertoast.showToast(
            msg: "网络请求异常",
            gravity: ToastGravity.CENTER,
          );
          JQUtils.printf('延时0.3s执行');
        });
        JQUtils.printf('网络请求异常');
        JQUtils.printf(e);
        JQUtils.printf(e.response);
        if (completeCallback != null) {
          completeCallback(e, null);
        }

        /// 实际上返回的是response的data数据
        return e.response;
      }
    }
  }
}


上一篇下一篇

猜你喜欢

热点阅读