delmin
delmin

Reputation: 2690

Reusing http headers

I'm trying to find a best way to reuse http headers in my http responses. Instead of writing it in string literal

 final http.Response response = await http.post(APIPath.somePath(),
      headers:{"Content-Type": "application/json","Authorization": "Bearer $_token"},
      body: json.encode(body));

I have made a custom class and get each header into a static function

class APIHeader {
  static Map<String, String> json() => {"Content-Type": "application/json"};
  static Map<String, String> form() => {"Content-Type": "multipart/form-data"};
  static Map<String, String> authorization(String token) =>
      {"Authorization": "Bearer $token"};
}

and call them wherever I need them which work great if there is only one header needed

  final http.Response response = await http.put(APIPath.somePath(),
      headers: APIHeader.json(), body: json.encode(body));

However I'm having a trouble if I need more then one header. I tried this..

final header = {}
  ..addAll(APIHeader.authorization(_token))
  ..addAll(APIHeader.json());
final http.Response response = await http.post(APIPath.somePath(),
          headers: header, body: json.encode(body));

which gives me an error

Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>'

Anyone have better idea how to reuse the headers?

Upvotes: 1

Views: 481

Answers (1)

delmin
delmin

Reputation: 2690

Thanks to @pskink I found using mergeMaps from 'package:collection/collection.dart' the best way to reuse headers and merge them into one map

 final http.Response response = await http.post(APIPath.somePath(),
      headers: [APIHeader.authorization(_token), APIHeader.json()]
          .reduce(mergeMaps),
      body: json.encode(body));

Upvotes: 1

Related Questions