toMultipartRequest function

Future<MultipartRequest> toMultipartRequest (
  1. List<PartValue> parts,
  2. String method,
  3. Uri uri,
  4. Map<String, String> headers
)

Implementation

Future<http.MultipartRequest> toMultipartRequest(
  List<PartValue> parts,
  String method,
  Uri uri,
  Map<String, String> headers,
) async {
  final baseRequest = http.MultipartRequest(method, uri);
  baseRequest.headers.addAll(headers);

  for (final part in parts) {
    if (part == null || part.value == null) continue;

    if (part.value is http.MultipartFile) {
      baseRequest.files.add(part.value);
    } else if (part.value is Iterable<http.MultipartFile>) {
      baseRequest.files.addAll(part.value);
    } else if (part is PartValueFile) {
      if (part.value is List<int>) {
        baseRequest.files.add(
          http.MultipartFile.fromBytes(part.name, part.value),
        );
      } else if (part.value is String) {
        baseRequest.files.add(
          await http.MultipartFile.fromPath(part.name, part.value),
        );
      } else {
        throw ArgumentError(
          'Type ${part.value.runtimeType} is not a supported type for PartFile'
          'Please use one of the following types'
          ' - List<int>'
          ' - String (path of your file) '
          ' - MultipartFile (from package:http)',
        );
      }
    } else {
      baseRequest.fields[part.name] = part.value.toString();
    }
  }
  return baseRequest;
}