Flutter Dio DioFactory

这个博客介绍了如何使用Dio库在Flutter中进行网络请求的封装,包括GET和POST方法,并添加了请求拦截器处理错误,特别是针对503错误的提示。同时,代码展示了如何根据不同的数据类型解析JSON响应并处理可能的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dio Flutter 网络请求pub DioFactory 封装 get post 请求 和 请求拦截头

dio_init.dart

class DioInit {
  static int timeOut = 30000; //30秒超时

  static Future<Dio> init() async {
    final String apiUrl = await Global.getSeverApiUrl();
    final String token = await Global.getUserToken();
    final Dio dio = Dio(BaseOptions(
        baseUrl: apiUrl + "/",
        sendTimeout: timeOut,
        contentType: 'application/json',
        method: "GET",
        connectTimeout: timeOut,
        headers: {"Access-Control-Allow-Origin": "*", 'auth': token}));
    return dio;
  }

  static Future<Dio> initP() async {
    final String apiUrl = await Global.getSeverApiUrl();
    final String token = await Global.getUserToken();
    final Dio dio = Dio(BaseOptions(
        baseUrl: apiUrl + "/",
        sendTimeout: timeOut,
        contentType: 'application/json',
        method: "POST",
        connectTimeout: timeOut,
        headers: {"Access-Control-Allow-Origin": "*", 'auth': token}));
    return dio;
  }

dio_factory.dart


///枚举字段
enum DioHttpType {
  get,
  post,
}

///dio 工厂类
class DioFactory<T extends dynamic> {
  final DioHttpType dioHttpType;
  final String apiUrl; // api路径
  final Map<String, dynamic>? queryParameters;
  final dynamic data;
  DioFactory(
    this.dioHttpType,
    this.apiUrl, {
    this.queryParameters,
    this.data,
  });

  static DioFactory<T> get<T>(
    String apiUrl, {
    Map<String, dynamic>? queryParameters,
  }) {
    return DioFactory<T>(DioHttpType.get, apiUrl,
        queryParameters: queryParameters);
  }

  static DioFactory<T> post<T>(
    String apiUrl, {
    Map<String, dynamic>? queryParameters,
    dynamic data,
  }) {
    return DioFactory<T>(DioHttpType.post, apiUrl,
        queryParameters: queryParameters, data: data);
  }

  Future<T?> response(
    T t, {
    required ResponseJsonFomratDart<T> responseJsonFomratDart,
  }) async {
    Dio? dio;
    var r;
    try {
      if (dioHttpType == DioHttpType.get) {
        dio = await DioInit.init();
        dio.interceptors.add(InterceptorsWrapper(onError: (e, h) {
          if (e.response == 503) {
            MotionToast.warning(
              title: Text(
                'Warning',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              toastDuration: Duration(seconds: 2),
              description: Text('服务器升级中'),
              animationType: ANIMATION.fromTop,
              position: MOTION_TOAST_POSITION.top,
              width: 300,
            ).show(Get.context!);
          }
        }));
        r = await dio.get<String>(apiUrl, queryParameters: queryParameters);
      } else if (dioHttpType == DioHttpType.post) {
        dio = await DioInit.initP();
        dio.interceptors.add(InterceptorsWrapper(onError: (e, h) {
          if (e.response == 503) {
            MotionToast.warning(
              title: Text(
                'Warning',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              toastDuration: Duration(seconds: 2),
              description: Text('服务器升级中'),
              animationType: ANIMATION.fromTop,
              position: MOTION_TOAST_POSITION.top,
              width: 300,
            ).show(Get.context!);
          }
        }));
        r = await dio.post<String>(apiUrl,
            data: data, queryParameters: queryParameters);
      }
      if (kDebugMode) { //如果是bug 环境
        log('\n✅请求状态:statusCode=${r.statusCode}, statusMessage=${r.statusMessage}\n请求方式:$dioHttpType\n请求完整apiUrl:${dio?.options.baseUrl}$apiUrl\n请求参数:$queryParameters\n返回值:$r');
      }
        
      //解析------------------
      
      if (t is List) {
        var httpResultModel =
            HttpResultModel.fromJson(json.decode(r.data.toString()));
        if (httpResultModel.responseStatus == 1) {
          return responseJsonFomratDart(httpResultModel);
        } else {
          MotionToast.error(
            title: Text(
              'Error',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            toastDuration: Duration(seconds: 2),
            description: Text('${httpResultModel.errorMessage}'),
            animationType: ANIMATION.fromTop,
            position: MOTION_TOAST_POSITION.top,
            width: 300,
          ).show(Get.context!);
        }
      }

      if (t is Map || t == null) {
        var httpResultModelTwo =
            HttpResultModelTwo.fromJson(json.decode(r.data.toString()));
        if (httpResultModelTwo.responseStatus == 1) {
          return responseJsonFomratDart(httpResultModelTwo);
        } else {
          MotionToast.error(
            title: Text(
              'Error',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            toastDuration: Duration(seconds: 2),
            description: Text('${httpResultModelTwo.errorMessage}'),
            animationType: ANIMATION.fromTop,
            position: MOTION_TOAST_POSITION.top,
            width: 300,
          ).show(Get.context!);
        }
      }
      if (t is bool || t is String) {
        var httpResultModelObj =
            HttpResultModelObj.fromJson(json.decode(r.data.toString()));
        if (httpResultModelObj.responseStatus == 1) {
          return responseJsonFomratDart(httpResultModelObj);
        } else {
          MotionToast.error(
            title: Text(
              'Error',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            toastDuration: Duration(seconds: 2),
            description: Text('${httpResultModelObj.errorMessage}'),
            animationType: ANIMATION.fromTop,
            position: MOTION_TOAST_POSITION.top,
            width: 300,
          ).show(Get.context!);
        }
      }
    } catch (e) {
      print(e.toString());
    }
    return null;
  }

  Future<T?> responseWaring(
    T t, {
    required ResponseJsonFomratDart<T> responseJsonFomratDart,
    Function(String? str)? waring,
  }) async {
    Dio? dio;
    var r;
    try {
      if (dioHttpType == DioHttpType.get) {
        dio = await DioInit.init();
        dio.interceptors.add(InterceptorsWrapper(onError: (e, h) {
          if (e.response == 503) {
            MotionToast.warning(
              title: Text(
                'Warning',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              toastDuration: Duration(seconds: 2),
              description: Text('服务器升级中'),
              animationType: ANIMATION.fromTop,
              position: MOTION_TOAST_POSITION.top,
              width: 300,
            ).show(Get.context!);
          }
        }));
        r = await dio.get<String>(apiUrl, queryParameters: queryParameters);
      } else if (dioHttpType == DioHttpType.post) {
        dio = await DioInit.initP();
        dio.interceptors.add(InterceptorsWrapper(onError: (e, h) {
          if (e.response == 503) {
            MotionToast.warning(
              title: Text(
                'Warning',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              toastDuration: Duration(seconds: 2),
              description: Text('服务器升级中'),
              animationType: ANIMATION.fromTop,
              position: MOTION_TOAST_POSITION.top,
              width: 300,
            ).show(Get.context!);
          }
        }));
        r = await dio.post<String>(apiUrl,
            data: data, queryParameters: queryParameters);
      }

      if (t is List) {
        var httpResultModel =
            HttpResultModel.fromJson(json.decode(r.data.toString()));
        if (httpResultModel.responseStatus == 1) {
          return responseJsonFomratDart(httpResultModel);
        } else {
          MotionToast.error(
            title: Text(
              'Error',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            toastDuration: Duration(seconds: 2),
            description: Text('${httpResultModel.errorMessage}'),
            animationType: ANIMATION.fromTop,
            position: MOTION_TOAST_POSITION.top,
            width: 300,
          ).show(Get.context!);
        }
      }

      if (t is Map || t == null) {
        var httpResultModelTwo =
            HttpResultModelTwo.fromJson(json.decode(r.data.toString()));
        if (httpResultModelTwo.responseStatus == 1) {
          return responseJsonFomratDart(httpResultModelTwo);
        } else {
          MotionToast.error(
            title: Text(
              'Error',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            toastDuration: Duration(seconds: 2),
            description: Text('${httpResultModelTwo.errorMessage}'),
            animationType: ANIMATION.fromTop,
            position: MOTION_TOAST_POSITION.top,
            width: 300,
          ).show(Get.context!);
        }
      }
      if (t is bool || t is String) {
        var httpResultModelObj =
            HttpResultModelObj.fromJson(json.decode(r.data.toString()));
        if (httpResultModelObj.responseStatus == 1) {
          return responseJsonFomratDart(httpResultModelObj);
        } else if (httpResultModelObj.responseStatus == 9) {
          var callBack = waring ?? (str) {};
          callBack(httpResultModelObj.errorMessage);
        } else {
          MotionToast.error(
            title: Text(
              'Error',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            toastDuration: Duration(seconds: 2),
            description: Text('${httpResultModelObj.errorMessage}'),
            animationType: ANIMATION.fromTop,
            position: MOTION_TOAST_POSITION.top,
            width: 300,
          ).show(Get.context!);
        }
      }
    } catch (e) {
      print(e.toString());
    }
    return null;
  }
}

typedef ResponseJsonFomratDart<T> = T Function(dynamic t);



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值