prepareRequest method

BaseRequest prepareRequest(
  1. HttpMethod method, {
  2. required Uri uri,
  3. required Map<String, String> headers,
  4. required Map<String, dynamic> params,
})
inherited

Implementation

http.BaseRequest prepareRequest(
  HttpMethod method, {
  required Uri uri,
  required Map<String, String> headers,
  required Map<String, dynamic> params,
}) {
  if (params.isNotEmpty) {
    params.removeWhere((key, value) => value == null);
  }

  http.BaseRequest request = http.Request(method.name(), uri);
  if (headers['content-type'] == 'multipart/form-data') {
    request = http.MultipartRequest(method.name(), uri);
    if (params.isNotEmpty) {
      params.forEach((key, value) {
        if (value is http.MultipartFile) {
          (request as http.MultipartRequest).files.add(value);
        } else {
          if (value is List) {
            value.asMap().forEach((i, v) {
              (request as http.MultipartRequest)
                  .fields
                  .addAll({"$key[$i]": v.toString()});
            });
          } else {
            (request as http.MultipartRequest)
                .fields
                .addAll({key: value.toString()});
          }
        }
      });
    }
  } else if (method == HttpMethod.get) {
    if (params.isNotEmpty) {
      params = params.map((key, value) {
        if (value is int || value is double) {
          return MapEntry(key, value.toString());
        }
        if (value is List) {
          return MapEntry(key + "[]", value);
        }
        return MapEntry(key, value);
      });
    }
    uri = Uri(
        fragment: uri.fragment,
        path: uri.path,
        host: uri.host,
        scheme: uri.scheme,
        queryParameters: params,
        port: uri.port);
    request = http.Request(method.name(), uri);
  } else {
    (request as http.Request).body = jsonEncode(params);
  }

  request.headers.addAll(headers);
  return request;
}