美文网首页
Flutter 网络请求的封装

Flutter 网络请求的封装

作者: 小王在努力 | 来源:发表于2020-11-11 09:43 被阅读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参数

    相关文章

      网友评论

          本文标题:Flutter 网络请求的封装

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