cache_nexus 1.1.0
cache_nexus: ^1.1.0 copied to clipboard
Offline-first caching for Flutter. Memory + Hive tiers, TTL, 5 cache policies, typed adapters, AES-GCM encryption, per-user isolation, reactive streams and offline sync.
Cache Nexus
Offline-first, debuggable caching and data orchestration for Flutter
Cache Nexus sits between your UI, your API and local storage. It caches in memory and on disk (Hive CE), applies one of five cache policies per call, keeps typed data across app restarts, encrypts what you ask it to, isolates data per user, pushes changes to widgets, queues offline writes, and shows everything in a dev panel.
Quick Start #
1. Add the dependency #
dependencies:
cache_nexus: ^1.1.0
2. Create the cache once #
import 'package:cache_nexus/cache_nexus.dart';
import 'package:flutter/foundation.dart';
late final CacheNexusManager cache;
Future<void> setupCache() async {
final disk = HiveCacheStorage(boxName: 'app_cache');
await disk.init();
cache = CacheNexusManager(
persistentStorage: disk,
mode: kReleaseMode ? CacheNexusMode.production : CacheNexusMode.dev,
);
// Teach the cache how to rebuild your classes after a restart.
cache.registerAdapter<Post>(
CacheAdapter.json(fromJson: Post.fromJson, toJson: (p) => p.toJson()),
);
}
3. Read through the cache #
final posts = await cache.get<List<Post>>(
key: 'posts',
fetcher: () => api.getPosts(),
ttl: const Duration(minutes: 10),
policy: CachePolicy.staleWhileRevalidate,
);
The first call fetches and stores; later calls (also after an app restart, also offline) are served from the cache. See doc/getting-started/quick-start.md for a full runnable app.
Features #
| Feature | Description |
|---|---|
| 5 cache policies | cacheFirst, networkFirst, cacheOnly, networkOnly, staleWhileRevalidate (exact semantics) |
| Two-tier storage | In-memory + persistent Hive CE; long and non-Latin keys handled |
| Typed data across restarts | Built-in decoding for common collections; CacheAdapter for your classes (covers List<T> and Map<String, T> too) |
| Request deduplication | Concurrent calls for the same key share one fetch |
| Offline support | Cached data is served when the network is down |
| Offline sync queue | SyncEngine with retries, exponential backoff and a failed-task list |
| Encryption | AesGcmEncryptor (AES-GCM, authenticated) + GZipCompressor via SecureCacheStorage |
| Per-user isolation | CacheContext scopes keys by user and role; invalidate on logout |
| Reactive UI | watch() streams and CacheNexusBuilder with loading/error builders |
| Dev tools | Floating overlay, live event panel, Dio interceptor, hit/miss stats |
Highlights #
Policies #
// Fresh when possible, cached when offline, real error when neither works
final feed = await cache.get<List<Post>>(
key: 'feed',
fetcher: () => api.getFeed(),
policy: CachePolicy.networkFirst,
);
staleWhileRevalidate returns the cached value immediately, even past its TTL, and refreshes in the background; watchers get the fresh value when it lands. networkFirst falls back to a fresh cached value and otherwise rethrows the original network error (for example the DioException).
Encryption #
final secure = SecureCacheStorage(
disk,
encryptor: AesGcmEncryptor.fromBase64(keyFromSecureStorage),
compressor: const GZipCompressor(),
);
Generate the key once with AesGcmEncryptor.generateKey() and keep it in the platform keystore (e.g. flutter_secure_storage). SimpleEncryptor is XOR obfuscation, not encryption, and is deprecated. See Security & Auth.
Per-user data #
cache.setContext(CacheContext(userId: user.id));
// ... on logout:
await cache.invalidateByContext(CacheContext(userId: user.id));
cache.clearContext();
Reactive widgets #
CacheNexusBuilder<List<Post>>(
cache: cache,
cacheKey: 'posts',
loadingBuilder: (_) => const CircularProgressIndicator(),
errorBuilder: (_, error, __) => Text('$error'),
builder: (_, posts) => PostList(posts: posts ?? const []),
);
Offline writes #
final sync = SyncEngine(
executor: (task) async {
await dio.request<void>(task.endpoint,
data: task.body, options: Options(method: task.method));
return true; // throwing or returning false = retry later
},
maxRetries: 5,
retryDelay: const Duration(seconds: 2), // 2s, 4s, 8s, ...
);
await sync.init();
sync.onTaskFailed.listen((task) => showRetryBanner(task));
Dev tools #
MaterialApp(
builder: (context, child) => CacheNexusOverlay(manager: cache, child: child!),
home: const HomeScreen(),
);
dio.interceptors.add(CacheNexusDioInterceptor(cache)); // redacts auth headers
Documentation #
| Section | Description |
|---|---|
| Getting Started | Installation, quick start, hello world |
| Guides | Core concepts, policies, storage & typed data, security, reactive, offline sync, dev tools |
| Examples | Blog app, auth flow, offline todo, snippets |
| Best Practices | Architecture, testing, performance, error handling, migration |
| API Reference | Class and method reference |
| FAQ | Common issues and troubleshooting |
Examples #
- example/: the showcase app (policies, security, reactive UI, sync queue, dev tools).
- Blog App: posts list and detail with Dio, policies, reactive UI and offline sync.
- Auth Flow: login, per-user isolation, encrypted storage, logout invalidation.
- Offline Todo: offline CRUD that survives restarts and syncs when back online.
Snippets #
| Snippet | Description |
|---|---|
| Basic CRUD | Create, read, update, delete cache entries |
| Custom Encryptor | Plug in your own cipher |
| Cache Warming | Pre-populate the cache on startup |
| Testing Patterns | Unit and widget testing |
| Request Dedup | Concurrent request handling |
| Cache Invalidation | Invalidation strategies |
| Stream Debounce | Prevent rapid UI rebuilds |
Installation #
From pub.dev #
dependencies:
cache_nexus: ^1.1.0
From Git #
dependencies:
cache_nexus:
git:
url: https://github.com/AbdAlftahSalem/cache-nexus.git
ref: main
Then run flutter pub get.
Upgrading from 1.0? There are no breaking API changes; read the 1.0 → 1.1 notes (storage moved to Hive CE, which reads your existing boxes).
Error Handling #
get() answers from the cache whenever the policy allows. When it cannot, the fetcher's error reaches you, so wrap network-backed calls:
try {
final profile = await cache.get<User>(
key: 'profile',
fetcher: () => api.getProfile(),
policy: CachePolicy.networkFirst,
);
} on DioException catch (e) {
// Network failed and nothing fresh was cached.
}
Roadmap #
Done #
- Memory cache, TTL, fetch flow, 5 policies, stats
- Request deduplication, stale-while-revalidate
- Hive persistence, two-tier architecture, typed adapters
- AES-GCM encryption, GZip compression, per-user isolation
- Reactive streams and
CacheNexusBuilder - Offline sync queue with retries, backoff and failed-task handling
- Dio interceptor and dev panel
Planned #
- Tag-based invalidation
- Cache warming / prefetch helpers, scheduled background refresh
- Dev panel export (JSON/CSV)
Contributing #
Contributions are welcome. See CONTRIBUTING.md for the development setup and the checks to run before opening a pull request.
Contact #
| Platform | Link |
|---|---|
| +972 59 804 5064 | |
| abdalftah.ps@gmail.com | |
| Abd Alftah Salem |
License #
MIT License - see LICENSE for details.
Built with ❤️ for Flutter developers who care about performance, simplicity, and debugging clarity.