Orientação gerada a partir de informações públicas. Apenas para referência.
http_interceptor é um plugin leve para Flutter que permite aos desenvolvedores interceptar solicitações e respostas HTTP, possibilitando modificações como adicionar cabeçalhos, registrar logs ou lidar com erros globalmente. Ele simplifica tarefas comuns como injeção de token de autenticação, registro de requisições/respostas e tratamento de erros em toda a aplicação. O pacote se integra perfeitamente ao cliente http embutido e suporta todas as principais plataformas, incluindo Android, iOS, Web, macOS, Windows e Linux. Projetado para simplicidade e flexibilidade, oferece uma API limpa para interceptação do tipo middleware sem exigir configurações complexas.
Casos de uso
Modificação de cabeçalho de solicitação global
Injeção de token de autenticação
Registro de solicitação/resposta
Tratamento de erros em todo o aplicativo
Monitoramento de solicitações da API
Depuração de tráfego HTTP
Principais recursos
Interceptação simples do estilo middleware
Suporta tanto solicitações quanto respostas
Compatibilidade multiplataforma
Integração fácil com cliente HTTP
Boilerplate mínimo
Cadeias de interceptadores extensíveis
Indicado para
Aplicativos que precisam de lógica HTTP centralizada
Desenvolvedores implementando fluxos de autenticação
Equipes que precisam de rastreamento HTTP amigável para depuração
Projetos com interações frequentes da API
Aqueles que buscam utilitários leves de HTTP
Considerações
Requer entendimento do ciclo de vida HTTP
Pode afetar o desempenho se usado em excesso
Os interceptores são executados sincronamente por padrão
Recuperação limitada de erros integrada
Não projetado para roteamento ou cache complexos
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
http_interceptor
This is a plugin that lets you intercept the different requests and responses from Dart's http package. You can use to add headers, modify query params, or print a log of the response.
Now that you actually have your interceptor implemented, now you need to use it. There are two general ways in which you can use them: by using the InterceptedHttp to do separate connections for different requests or using a InterceptedClient for keeping a connection alive while making the different http calls. The ideal place to use them is in the service/provider class or the repository class (if you are not using services or providers); if you don't know about the repository pattern you can just google it and you'll know what I'm talking about. 😉
Using interceptors with Client
Normally, this approach is taken because of its ability to be tested and mocked.
Here is an example with a repository using the InterceptedClient class.
The ResponseBodyDecoding extension adds a few lightweight helpers on Response for common JSON use cases:
final response = await client.get(
'$baseUrl/weather'.toUri(),
params: {'id': '$id'},
);
// Dynamically-typed JSON value (Map/List/primitive or null on empty body).finalObject? json = response.jsonBody;
// JSON object as a map (throws if body is empty or not a JSON object).finalMap<String, dynamic> data = response.jsonMap;
// JSON array as a list (throws if body is empty or not a JSON array).finalList<dynamic> items = response.jsonList;
Decoding responses into models
The ResponseBodyDecoding extension provides helpers to turn JSON responses into strongly-typed models with minimal boilerplate.
Sometimes you need to retry a request due to different circumstances, an expired token is a really good example. Here's how you could potentially implement an expired token retry policy with http_interceptor.
classExpiredTokenRetryPolicyextendsRetryPolicy{
@overrideintget maxRetryAttempts => 2;
@overrideboolshouldAttemptRetryOnException(Exception reason, BaseRequest request) {
// Log the exception for debuggingprint('Request failed: ${reason.toString()}');
print('Request URL: ${request.url}');
// Retry on network exceptions, but not on client errorsreturn reason isSocketException || reason isTimeoutException;
}
@overrideFuture<bool> shouldAttemptRetryOnResponse(BaseResponse response) async {
if (response.statusCode == 401) {
// Perform your token refresh here.print('Token expired, refreshing...');
returntrue;
}
returnfalse;
}
}
You can also set the maximum amount of retry attempts with maxRetryAttempts property or override the shouldAttemptRetryOnException if you want to retry the request after it failed with an exception.
RetryPolicy Interface
The RetryPolicy abstract class provides the following methods that you can override:
shouldAttemptRetryOnException(Exception reason, BaseRequest request): Called when an exception occurs during the request. Return true to retry, false to fail immediately.
shouldAttemptRetryOnResponse(BaseResponse response): Called after receiving a response. Return true to retry, false to accept the response.
maxRetryAttempts: The maximum number of retry attempts (default: 1).
delayRetryAttemptOnException({required int retryAttempt}): Delay before retrying after an exception (default: no delay).
delayRetryAttemptOnResponse({required int retryAttempt}): Delay before retrying after a response (default: no delay).
Using Retry Policies
To use a retry policy, pass it to the InterceptedClient or InterceptedHttp:
final client = InterceptedClient.build(
interceptors: [WeatherApiInterceptor()],
retryPolicy: ExpiredTokenRetryPolicy(),
);
Sometimes it is helpful to have a cool-down phase between multiple requests. This delay could for example also differ between the first and the second retry attempt as shown in the following example.
You can achieve support for self-signed certificates by providing InterceptedHttp or InterceptedClient with the client parameter when using the build method on either of those, it should look something like this:
Note: It is important to know that since both HttpClient and IOClient are part of dart:io package, this will not be a feature that you can perform on Flutter Web (due to BrowserClient and browser limitations).
We migrated our roadmap to better suit the needs for development since we use ClickUp as our task management tool.
Troubleshooting
Open an issue and tell me, I will be happy to help you out as soon as I can.
Contributions
Contributions are always welcomed and encouraged, we will always give you credit for your work on this section. If you are interested in maintaining the project on a regular basis drop me a line at [me@codingale.dev](mailto:me@codingale.dev).
Contributors
Thanks to all the wonderful people contributing to improve this package. Check the Emoji Key for reference on what means what!