Flutter Dio封裝與使用

依賴庫版本

dio: 2.0.14

1.簡單封裝

import 'package:dio/dio.dart';
import 'dart:async';

/*
 * 封裝 restful 請求
 *
 * GET、POST、DELETE、PATCH
 * 主要作用為統(tǒng)一處理相關(guān)事務(wù):
 *  - 統(tǒng)一處理請求前綴;
 *  - 統(tǒng)一打印請求信息;
 *  - 統(tǒng)一打印響應(yīng)信息;
 *  - 統(tǒng)一打印報錯信息;
 */
class DioUtils {
  /// global dio object
  static Dio dio;

  /// default options
  static const String API_PREFIX = 'https://novel.dkvirus.com/api/v1';
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  ///Get請求測試
  static void getHttp() async {
    try {
      Response response = await Dio().get("http://www.google.cn");
      print("response$response");
    } catch (e) {
      print(e);
    }
  }

  ///Post請求測試
  static void postHttp<T>(
    String url, {
    parameters,
    Function(T t) onSuccess,
    Function(String error) onError,
  }) async {

    ///定義請求參數(shù)
    parameters = parameters ?? {};
    //參數(shù)處理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    try {
      Response response;
      Dio dio = createInstance();
      response = await dio.post(url, data: parameters);
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(response.data);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('響應(yīng)數(shù)據(jù):' + response.toString());
    } catch (e) {
      print('請求出錯:' + e.toString());
      onError(e.toString());
    }
  }

  /// request method
  //url 請求鏈接
  //parameters 請求參數(shù)
  //metthod 請求方式
  //onSuccess 成功回調(diào)
  //onError 失敗回調(diào)
  static Future<Map> request<T>(String url,
      {parameters,
      method,
      Function(T t) onSuccess,
      Function(String error) onError}) async {
    parameters = parameters ?? {};
    method = method ?? 'GET';

    /// 請求處理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印:請求地址-請求方式-請求參數(shù)
    print('請求地址:【' + method + '  ' + url + '】');
    print('請求參數(shù):' + parameters.toString());

    Dio dio = createInstance();
    //請求結(jié)果
    var result;
    try {
      Response response = await dio.request(url,
          data: parameters, options: new Options(method: method));
      result = response.data;
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(result);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('響應(yīng)數(shù)據(jù):' + response.toString());
    } on DioError catch (e) {
      print('請求出錯:' + e.toString());
      onError(e.toString());
    }

    return result;
  }

  /// 創(chuàng)建 dio 實例對象
  static Dio createInstance() {
    if (dio == null) {
      /// 全局屬性:請求前綴、連接超時時間、響應(yīng)超時時間
      var options = BaseOptions(
        connectTimeout: 15000,
        receiveTimeout: 15000,
        responseType: ResponseType.plain,
        validateStatus: (status) {
          // 不使用http狀態(tài)碼判斷狀態(tài),使用AdapterInterceptor來處理(適用于標(biāo)準(zhǔn)REST風(fēng)格)
          return true;
        },
        baseUrl: "http://poetry.huhustory.com/",
      );

      dio = new Dio(options);
    }

    return dio;
  }

  /// 清空 dio 對象
  static clear() {
    dio = null;
  }
}

2.使用

 @override
  Future initState() {
    // TODO: implement initState
    super.initState();
    FormData formData = new FormData.from({
      "uuid": "9dad1c81889ff0ea8c8c5ade6a5e36e3",
      "sign": "",
      "sso_id": "",
      "own_version": "100",
      "channel": "ios",
      "dev_os_version": "iOS12.3.1",
      "timestamp": "1564974676",
      "screen_size": "[375,667]",
      "is_jailbreak": 0,
      "os": "ios",
      "device_name": "iPhone6S",
      "os_version": "",
      "country_code": "CN",
      "ios_version": "1.0.0",
    });
    DioUtils.postHttp(
      "huhuapi/firstnew/indexnew.html",
      parameters: formData,
      onSuccess: (data) {
        Toast.show('來了');
      },
      onError: (error) {
        Toast.show(error);
      },
    );
  }

未完,待續(xù)~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容