Flutter 및 Dart 앱에서 네트워크 요청에 대해 표준 캐시 헤더를 기반으로 HTTP 응답을 저장하고 재사용함으로써 HTTP 클라이언트 성능을 향상시키는 Dart 패키지입니다. 중복된 네트워크 트래픽을 줄이고 응답 시간을 개선합니다. 뉴스 피드, 제품 목록 또는 어떤 API 기반 UI든 효율적인 데이터 가져오기가 필요한 애플리케이션에 적합합니다. 기존 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