How to set base url to flutter http package?

Viewed 1719

I tried using http package of flutter and create a custom client with headers.

Code

class ApiClient extends http.BaseClient {
  final http.Client _inner;
  
  ApiClient(this._inner);

  _setHeaders() => {
    'Content-type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer token here...'
  };

  Future<http.StreamedResponse> send(http.BaseRequest request) {
    request.headers.addAll(_setHeaders());
    return _inner.send(request);
  }
}

How can I add a base URL to my custom client?

2 Answers

Since ApiClient inherits http.BaseClient, you should be able to have access to other methods as well. Simply access the method on your ApiClient for example.

var baseUrl = Uri.parse('https://example.com/');
var response = await ApiClient.post(baseUrl);

I use a similar approach on my projects:

class ApiClient extends http.BaseClient {
  final http.Client _inner;
  final String baseUrl;
  
  ApiClient(this._inner, this.baseUrl);

  Uri url(String path, [Map<String, String?>? queryParameters]) {
    return Uri.parse('$baseUrl$path').replace(queryParameters: queryParameters);
  }

  // other methods ...
}

Usage sample:


final api = ApiClient(inner, 'https://testhost/api/v1');
final response = await api.post(api.url('/test', {'q': 'a'}));

Related