一個 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