美文网首页
dio升级到4.0之后的网络请求

dio升级到4.0之后的网络请求

作者: 心旷则神怡 | 来源:发表于2022-04-16 14:11 被阅读0次
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'config.dart';

class HttpRequest {
  static final BaseOptions baseOptions = BaseOptions(baseUrl: HttpConfig.baseURL, connectTimeout: HttpConfig.timeout);
  static final Dio dio = Dio();

//get请求
  static Future<T> request<T>(String url, {
    Map<String, dynamic>? params,
    Interceptor? inter
  }) async {

    SharedPreferences preferences = await SharedPreferences.getInstance();
    if(preferences.getString("user_id") == null){
      requestUser_id();
    }
    //创建默认的全局拦截器,用到可以添加,这里暂时下加上去
    Interceptor dIter = InterceptorsWrapper();
    List<Interceptor> inters = [dIter];
    //请求单独拦截器
    if (inter != null) {
      inters.add(inter);
    }
    //统一添加到拦截器中
    dio.interceptors.addAll(inters);

    //2.发送网络请求
    try {
      Response response = await dio.get(
          url,
          queryParameters: params,
          options: Options(
            headers: {
              "key":"value",
            }
          )
      );
      print(response);
      return response.data;
    }on DioError catch (error){
      return Future.error(error);
    }
  }

//post请求
  static Future<T> post<T>(String url, {
    Map<String, dynamic>? params,
    Interceptor? inter
  }) async {

    try {
      Response res = await dio.post(
        url,
        data: params,
        options: Options(
          headers: {
              "key":"value",
          },
        )
      );
      // print(res.data);
      return res.data;
    }on DioError catch (error){
      return Future.error(error);
    }
  }

//上传文件
  static Future<T> uploadFile<T>(String url, File image, Map<String, dynamic> fileMap) async {
    final options = Options();
    options.headers = {
         "key":"value",
    };
    try{
      FormData formData = FormData.fromMap(fileMap);
      var response = await dio.post(url, data: formData, options: options);
      return response.data;
    }on DioError catch (error){
      return Future.error(error);
    }
  }
}

相关文章

网友评论

      本文标题:dio升级到4.0之后的网络请求

      本文链接:https://www.haomeiwen.com/subject/noqhertx.html