一个 Dart 包,通过为 Flutter 和 Dart 应用中的网络请求添加透明缓存来提升 HTTP 客户端性能。它根据标准缓存头存储并重用 HTTP 响应,减少冗余网络流量并提高响应速度。适用于需要高效数据获取的应用场景,如新闻动态、商品列表或任何基于 API 的用户界面。该包可与现有 http 客户端无缝集成,并支持 Android、iOS、Linux、macOS 和 Windows 等主要平台。
适合场景
缓存 API 响应以减少加载时间
通过离线数据访问提升应用性能
减少移动应用中的带宽使用
将频繁访问的数据本地存储
在网络中断后启用更快的重新加载
主要特点
与 http 客户端的无缝集成
支持标准的 HTTP 缓存头
自动缓存管理
跨平台兼容性
轻量且易于实现
适合对象
频繁调用 API 的应用
离线优先的应用程序
性能关键的 Flutter 项目
寻求简单缓存解决方案的开发者
面向多个平台的移动和桌面应用程序
使用建议
需要在服务器端正确配置缓存头
可能会随时间增加本地存储使用量
缓存失效必须谨慎处理
不适合用于高度敏感的实时数据
与完整的缓存框架相比,自定义选项有限
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
HttpTools
A comprehensive collection of Dart and Flutter packages for HTTP request handling, providing intercepting, logging, and caching capabilities to enhance your network operations.
✅ Smart Binary Detection - Clean logs without garbage data
✅ Production Ready - Configurable for development vs production
✅ Human Readable - Clean, structured log format
Log Output Examples:
[a1b2c3d4] --> GET https://api.example.com/users/123
[a1b2c3d4] authorization: Bearer ***
[a1b2c3d4] content-type: application/json
[a1b2c3d4] --> END GET
[a1b2c3d4] <-- 200OK (145ms)
[a1b2c3d4] content-type: application/json
[a1b2c3d4] {"id": 123, "name": "John Doe"}
[a1b2c3d4] <-- END
Usage:
import'package:http_client_logger/http_client_logger.dart';
import'package:logging/logging.dart'hideLevel;
// Set up loggingLogger.root.onRecord.listen((record) => print(record.message));
// Configure loggerHttpClientProxy(
interceptors: [
HttpLogger(
level: Level.body, // basic | headers | body
logBodyContentTypes: {'application/json'}, // Only log JSON as text
),
],
)
http_client_cache
HTTP caching with disk/memory storage - Improve performance and reduce network usage
Key Features:
✅ RFC 7234 Compliant - Standard HTTP caching behavior
✅ Memory & Disk Storage - Choose what fits your needs
✅ Cache-Control Support - Respects server cache directives
✅ Stale-While-Revalidate - Serve stale content while updating
✅ Stale-If-Error - Fallback to cache when network fails
✅ Automatic Cleanup - LRU eviction and size limits
✅ Private Content Filtering - Secure handling of sensitive data
Cache Behavior Examples:
Cache miss for https://api.example.com/posts/1 # First requestCache hit for https://api.example.com/posts/1 # Served from cacheCache entry expired for https://api.example.com/posts/1 # Needs refreshServing stale content due to network error # Stale-if-error fallback
HttpClientProxy(
interceptors: [
if (kDebugMode) HttpLogger(level: Level.body), // Only log in debugAuthInterceptor(apiKey),
cache,
],
)
Custom Cache Control
classCacheControlInterceptorextendsHttpInterceptor{
@overrideFutureOr<OnResponse> onResponse(StreamedResponse response) {
final headers = Map<String, String>.from(response.headers);
// Cache API responses with resilience featuresif (response.request?.url.path.startsWith('/api/') ?? false) {
headers['cache-control'] =
'max-age=300, stale-while-revalidate=60, stale-if-error=3600';
// Cache for 5 min, serve stale for 1 min while revalidating,// serve stale for 1 hour if network fails
}
returnOnResponse.next(response.copyWith(headers: headers));
}
}
🔗 Framework Compatibility
Works seamlessly with popular HTTP packages:
✅ http - A composable, multi-platform, Future-based API for HTTP requests.
✅ chopper - An http client generator using source_gen, inspired by Retrofit
✅ retrofit - An dio client generator using source_gen and inspired by Chopper and Retrofit
Note:dio and retrofit (which uses dio) require the dio_compatibility_layer package to work with the standard http package that these interceptors depend on.
dependencies:http:^1.2.0dio_compatibility_layer:^3.0.0# Required for dio/retrofit compatibility
📊 Performance Considerations
Development vs Production:
HttpClientProxy(
interceptors: [
// Production: Only basic loggingif (kReleaseMode) HttpLogger(level: Level.basic),
// Development: Full logging with bodies if (kDebugMode) HttpLogger(level: Level.body),
// Always cache for better performance
cache,
],
)
Memory Management:
Cache automatically manages size with LRU eviction
Use cache.clearCache() when memory is low
Use cache.deletePrivateContent() when user logs out