Sorry if this question so basic, but I am new to flutter and recently couldn\'t find a good way to set a default headers in the HTTP request I can extend the class or wrap a fun
Just expanding on @Radek Manasek idea of a custom Client
, I'm overriding all the methods so you don't have to write them again.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
class MyClient extends http.BaseClient {
final Map _defaultHeaders;
http.Client _httpClient = http.Client();
MyClient(this._defaultHeaders);
@override
Future send(http.BaseRequest request) {
return _httpClient.send(request);
}
@override
Future get(url, {Map headers}) {
return _httpClient.get(url, headers: _mergedHeaders(headers));
}
@override
Future post(url, {Map headers, dynamic body, Encoding encoding}) {
return _httpClient.post(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
}
@override
Future patch(url, {Map headers, dynamic body, Encoding encoding}) {
return _httpClient.patch(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
}
@override
Future put(url, {Map headers, dynamic body, Encoding encoding}) {
return _httpClient.put(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
}
@override
Future head(url, {Map headers}) {
return _httpClient.head(url, headers: _mergedHeaders(headers));
}
@override
Future delete(url, {Map headers}) {
return _httpClient.delete(url, headers: _mergedHeaders(headers));
}
Map _mergedHeaders(Map headers) =>
{...?_defaultHeaders, ...?headers};
}