applyHeaders function

Request applyHeaders(
  1. Request request,
  2. Map<String, String> headers, {
  3. bool override = true,
})

Creates a new Request by copying request and adding the provided headers to the result.

If request already has headers with keys provided in headers and override is true (default), the conflicting headers will be replaced.

final newRequest = applyHeaders(request, {
  'Authorization': 'Bearer <token>',
  'Content-Type': 'application/json',
});

Implementation

Request applyHeaders(
  Request request,
  Map<String, String> headers, {
  bool override = true,
}) {
  final LinkedHashMap<String, String> headersCopy = LinkedHashMap(
    equals: (a, b) => a.toLowerCase() == b.toLowerCase(),
    hashCode: (e) => e.toLowerCase().hashCode,
  );
  headersCopy.addAll(request.headers);

  for (final entry in headers.entries) {
    if (!override && headersCopy.containsKey(entry.key)) continue;
    headersCopy[entry.key] = entry.value;
  }

  return request.copyWith(headers: headersCopy);
}