Flutter Dio http简单封装与使用


初次封装版本,后续更新完善。不足的地方欢迎提供意见,非常乐意学习请教。

dio简单封装

import 'dart:convert';
import 'dart:io';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:yunxiaobao/utils/shared_util.dart';
import '../config/dio_config.dart';

/// dio统一封装
/// xxx 2020-09-21 add
class DioUtil {
  /// 实例
  static DioUtil _instance;

  /// token前缀
  static const String _refreshTokenKey = 'Admin-Refresh-Token';

  /// token前缀2
  static const String _accessTokenKey = "Bearer ";

  /// 获取实例
  static DioUtil getInstance() {
    if (_instance == null) _instance = DioUtil();
    return _instance;
  }

  /// 默认配置
  Dio dio = Dio();
  DioUtil() {
    // 请求地址
    dio.options.baseUrl = DioConfig.baseUrl;
    // 超时时间
    dio.options.connectTimeout = 5000;
    // 接受数据超时时间
    dio.options.receiveTimeout = 3000;
    // 打印日志
    dio.interceptors.add(LogInterceptor(responseBody: DioConfig.isDebug));
    // SSL证书策略
    noSSl();
  }

  /// get请求方法
  get(String url,
      {Map<String, dynamic> params, Function success, Function error}) {
    _requestHttp(url, success, 'get', params, error);
  }

  /// post请求方法
  post(String url,
      {Map<String, dynamic> params, Function success, Function error}) {
    _requestHttp(url, success, 'post', params, error);
  }

  // 请求
  _requestHttp(String url, Function successCallBack,
      [String method,
      Map<String, dynamic> params,
      Function errorCallBack]) async {
    // 从本地缓存拿到两个token
    String accessToken = await SharedUtil.getValue('access_tokenKey');
    String refreshToken = await SharedUtil.getValue('refresh_token');
    // 设置头
    dio.options.headers = {
      "authorization": _accessTokenKey + accessToken,
      "Cookie": _refreshTokenKey + refreshToken,
    };
    Response response;

    /// 发起请求
    try {
      // get请求
      if (method == 'get') {
        if (params != null && params.isNotEmpty) {
          response = await dio.get(url, queryParameters: params);
        } else {
          response = await dio.get(url);
        }
      }
      // post请求
      else if (method == 'post') {
        if (params != null && params.isNotEmpty) {
          response = await dio.post(url, data: params);
        } else {
          response = await dio.post(url);
        }
      }
    }

    /// 请求错误处理
    on DioError catch (error) {
      // 错误类型
      String msg = error.message;
      if (error.type == DioErrorType.CANCEL)
        msg = "连接被取消";
      else if (error.type == DioErrorType.CONNECT_TIMEOUT)
        msg = "请求时超时";
      else if (error.type == DioErrorType.SEND_TIMEOUT)
        msg = "连接超时";
      else if (error.type == DioErrorType.RECEIVE_TIMEOUT) msg = "接收超时";
      if (errorCallBack != null) _error(errorCallBack, msg);
      return;
    }

    /// 根据服务器响应结果进行处理(可根据返回状态码处理)
    // String strData = json.encode(response.data['data']); // 转json字符串
    // Map<String, dynamic> dataMap = json.decode(strData); // 转map(json)
    Map<String, dynamic> dataMap = response.data;
    if (dataMap == null || dataMap['code'] == null)
      _error(errorCallBack, "返回参数异常");
    else if (dataMap['code'] == 401)
      _error(errorCallBack, "没有权限");
    else
      successCallBack(dataMap);
  }

  // 是否忽略SSL证书
  noSSl() {
    if (DioConfig.noSSL)
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) {
          return true;
        };
      };
  }

  // 错误处理
  _error(Function errorCallBack, String msg) {
    errorCallBack(msg);
  }
}

配置类

/// 请求统一请求的配置
/// xxx 2020-09-23 add
class DioConfig {
  /// 是否打印请求日志
  static const bool isDebug = false;

  /// 忽略证书
  static const bool noSSL = true;

  /// 请求地址
  static const String baseUrl = "https://easy-mock.com";
}

接口地址类

/// 测试相关接口
/// xxx 2020-09-23 add
class TestApi {
  /// 测试接口1
  static String test = "/mock/5f6b573cb766f82502c8a3b2/api/test";

  /// 测试接口2
  static String test2 = "/mock/5f6b573cb766f82502c8a3b2/api/test2";

  /// 测试接口2
  static String test3 = "/mock/5f6b573cb766f82502c8a3b2/api/test3";
}

本地缓存读取工具类

import 'package:shared_preferences/shared_preferences.dart';

/// 本地储存工具类
/// xxx 2020-09-23 add
class SharedUtil {
  /// 根据Key取值
  static getValue(String key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String value = sp.get(key);
    if (value == null) return "";
    return value;
  }

  /// 根据key设置值
  static setValue(String key, String value) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString(key, value);
  }
}

简单使用

  /// 测试
  // 方法
  _loginBtn() async {
    // 调用方法
    DioUtil.getInstance().get(
      TestApi.test3,
      success: (data) {
      	// 成功返回结果
        print(data);
      },
      error: (error) {
      	// 失败返回结果
        print('失败' + error);
      },
    );
  }

使用相关包

dio: ^3.0.10
shared_preferences: 0.5.10

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页