Flutter 网络请求的封装

2020-11-11  本文已影响0人  小王在努力

1、导入相关的库

dio: ^3.0.9

2、定义枚举

enum HttpMethod{
  Get,
  Post,
  Put,
  Delete
}

3、代码封装

  static Future<String> method(HttpMethod method,String url,String txCode,Map bodys,Map header) async{
    var params = new Map<String, dynamic>.from(bodys);
    var headers = new Map<String, dynamic>.from(header);
    String platform;
    if(Platform.isAndroid) {
      platform = "Android";
    } else if(Platform.isIOS) {
      platform = "IOS";
    }
    headers['OS'] = platform;

    Dio dio = new Dio();
    BaseOptions options = BaseOptions(headers:headers);
    options.connectTimeout = 10 * 1000;
    options.receiveTimeout = 20 * 1000;
    dio.options = options;
    var stringUrl = url + txCode;
    Response response = null;
    switch (method){
      case HttpMethod.Get:{
        response = await dio.get(stringUrl,queryParameters: params);
      }break;
      case HttpMethod.Post:{
        response = await dio.post(stringUrl,queryParameters:params);
      }break;
      case HttpMethod.Put:{
        response = await dio.put(stringUrl,queryParameters:params);
      }break;
      case HttpMethod.Delete:{
        response = await dio.delete(stringUrl,queryParameters:params);
      }break;
    }
    if(response.statusCode == 200){
      return await response.data.toString();
    }else{
      return "";
    }
  }

注意
a、method:请求方式GET/POST
b、url :域名
c、txCode:域名后面跟随的字段
d、bodys :参数
e、header:header参数

上一篇下一篇

猜你喜欢

热点阅读