1
votes

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?

1
final header = {} -> final header = <String, String>{} - pskink
@pskink Thanks... that worked for that error.. but is there any better way to reuse this headers? I found a bit tedious to initialise that header variable and then add those headers there.. Isn't there any better solution? - delmin
write a top level function that returns the map, or use mergeMaps for example (just found it one minute ago so i dont know how it works in practice) - pskink
import 'package:collection/collection.dart'; var maps = [{1: 10}, {2: 20}, {3: 30}]; print(maps); print(maps.reduce(mergeMaps)); - pskink
@ChinkySight well sure but how about adding token into that enums.. You can't change or modify enum so you basically end up with bits and peaces of the headers which you will have to build together.. That isn't really convenience way of doing it. Or do you have any other trick with enums under the sleeve? - delmin

1 Answers

1
votes

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));