markdown Flutter dio封装

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Flutter dio封装相关的知识,希望对你有一定的参考价值。

# Flutter dio 框架封装

使用单例模式保证全局只有一个dio,添加拦截器, 添加cookie永久保存

```dart
import 'dart:io';

//import 'package:connectivity/connectivity.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:vehicle_transfer/screens/common/EventBus.dart';
// import 'package:fluro/fluro.dart';
// import 'package:vehicle_transfer/utils/Global.dart';

import './ApplicationUtils.dart';
import './SharedPreUtils.dart';

import '../beans/VTResponse.dart';

class HttpUtils {
  static final HttpUtils _singleton = HttpUtils._internal();

  factory HttpUtils() {
    return _singleton;
  }

  HttpUtils._internal();

  static CancelToken cancelToken;

  Dio get dio {
    Dio dio = new Dio();

    dio.options.connectTimeout = 20000; //5s
    dio.options.receiveTimeout = 20000;
    dio.options.contentType =
        ContentType.parse("application/json; charset=utf-8");

    dio.interceptors.add(
      InterceptorsWrapper(onRequest: (RequestOptions options) async {
        eventBus.fire(LoadingInEvent(true));
        return options; //continue
      }, onResponse: (Response response) async {
        final int statusCode = response.statusCode;

        if (statusCode == 200 || statusCode == 201) {}

        print(
            "Response From:${response.request.method}, ${response.request.baseUrl} ${response.request.path}");
        print("Response From:${response.toString()}");

        eventBus.fire(LoadingInEvent(false));
        return response; // continue
      }, onError: (DioError e) {
        eventBus.fire(LoadingInEvent(false));

        return e;
      }),
    );

    dio.interceptors.add(LogInterceptor(responseBody: true)); //开启请求日志

    CookieJar cj = new PersistCookieJar(dir: ApplicationUtils.cookiePath);
    dio.interceptors.add(CookieManager(cj));

    return dio;
  }

  // get 请求封装
  get(url, {options, data = Null}) async {
    print('start------> $url ,$data, date: ${new DateTime.now().toString()}');

    VTResponse vtResponse;

    String fullUrl =
        ApplicationUtils.prefs.getString(SharedPreUtils.backendUrl) + url;

    try {
      await HttpUtils()
          .dio
          .get(
            fullUrl,
            queryParameters: data != Null ? data : {},
            cancelToken: cancelToken,
          )
          .then((response) {
        vtResponse = VTResponse.fromJson(response.data);

        print(
            'end ------> ,$vtResponse, date: ${new DateTime.now().toString()}');
      });
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('get Cancel ' + e.message);
      } else {
        print('get Error:$e');
      }
    }

    return vtResponse;
  }

  // post请求封装
  post(url, {options, data = Null}) async {
    print('start------> $url ,$data, date: ${new DateTime.now().toString()}');

    VTResponse vtResponse;

    String fullUrl =
        ApplicationUtils.prefs.getString(SharedPreUtils.backendUrl) + url;

    try {
      await HttpUtils()
          .dio
          .post(
            fullUrl,
            data: data != Null ? data : {},
            cancelToken: cancelToken,
          )
          .then((response) {
        vtResponse = VTResponse.fromJson(response.data);

        print(
            'end ------> ,$vtResponse, date: ${new DateTime.now().toString()}');
      });
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('post请求取消! ' + e.message);
      } else {
        print('post请求发生错误:$e');
      }
    }

    return vtResponse;
  }
}

```

以上是关于markdown Flutter dio封装的主要内容,如果未能解决你的问题,请参考以下文章

Flutter Dio源码分析(四)--封装

Flutter--网络请求dio封装网络请求框架

Flutter网络请求Dio库的使用及封装

基于dio库封装flutter项目的标准网络框架

flutter dio网络请求封装经过多次修改更新 呕心沥血而成的封装版本 返回future 加入token的版本

赠书|Flutter-dio封装,满足你的需要