Smart Cache

Offline-first, debuggable data orchestration layer for Flutter

pub.dev license flutter stars


Smart Cache is not just a caching library. It is a full data orchestration layer between UI, API, and local storage. It handles caching, offline fallback, request deduplication, security, reactive streams, and built-in developer debugging tools -- so you don't have to.


Quick Start (5 minutes)

1. Add dependency

# pubspec.yaml
dependencies:
  cache_nexus: ^1.0.0

2. Initialize & cache

import 'package:cache_nexus/cache_nexus.dart';

final cache = CacheNexusManager(
  memoryStorage: MemoryCacheStorage(),
);

final users = await cache.get<List<String>>(
  key: 'users',
  fetcher: () async => ['Alice', 'Bob', 'Charlie'],
  ttl: Duration(hours: 1),
);

print(users); // ['Alice', 'Bob', 'Charlie']
// Next call with same key returns instantly from cache!

That's it. See docs/getting-started/quick-start.md for the full runnable example.


Features

Feature Description
5 Cache Policies cacheFirst, networkFirst, cacheOnly, networkOnly, staleWhileRevalidate
Two-Tier Storage Fast in-memory + persistent Hive
Request Deduplication Concurrent requests share one network call
Offline Support Automatic fallback to persistent cache
Offline Sync Queue Tasks retry when connectivity returns
Security Layer Encryption + compression decorators
Auth-Aware Caching Isolate cache by user ID and role
Reactive Streams watch() API + CacheNexusBuilder widget
Dev Tools Floating debug button, live event panel, stats
Cache Stats Hit/miss/fetch/error tracking with hit rate

Documentation

Section Description
Getting Started Installation, quick-start, hello-world
Guides Core concepts, policies, storage, security, reactive, offline, dev tools
Examples Real-world examples with code snippets
Best Practices Architecture, testing, performance, migration
API Reference Complete class/method documentation
FAQ Common issues and troubleshooting

Examples

Blog App

A complete blog app with posts list, detail view, cache policies, reactive UI, and offline sync.

Features demonstrated:

  • CacheNexusBuilder for auto-rebuilding UI
  • Cache policies (cacheFirst vs networkFirst)
  • Request deduplication
  • Dev tools overlay

See docs/examples/blog-app/ for full code.

Auth Flow

Login, user context switching, cache isolation between users, and secure logout.

Features demonstrated:

  • Auth-aware caching
  • CacheContext for user isolation
  • Smart invalidation by context
  • Encrypted storage for sensitive data

See docs/examples/auth-flow/ for full code.

Offline Todo

Create, edit, and delete todos offline with automatic sync when online.

Features demonstrated:

  • SyncEngine for offline queue
  • Auto-retry on connectivity return
  • Persistent cache across app restarts
  • NetworkStatus monitoring

See docs/examples/offline-todo/ for full code.


Code Snippets

Snippet Description
Basic CRUD Create, read, update, delete cache entries
Custom Encryptor Implement your own encryption
Cache Warming Pre-populate 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 (when published)

dependencies:
  cache_nexus: ^1.0.0

From Git

dependencies:
  cache_nexus:
    git:
      url: https://github.com/AbdAlftahSalem/cache-nexus.git
      ref: main

From local path

dependencies:
  cache_nexus:
    path: ../cache_nexus

Then run:

flutter pub get

Best Practices

Singleton Pattern

// app_cache.dart
class AppCache {
  static final AppCache _instance = AppCache._();
  factory AppCache() => _instance;
  AppCache._();

  final CacheNexusManager cache = CacheNexusManager(
    memoryStorage: MemoryCacheStorage(),
    persistentStorage: HiveCacheStorage(boxName: 'app_cache'),
    mode: kReleaseMode ? CacheNexusMode.production : CacheNexusMode.dev,
  );
}

Error Handling

final data = await cache.get<User>(
  key: 'profile',
  fetcher: () => api.getProfile(),
  ttl: Duration(minutes: 15),
);
// Data is always returned (from cache, network, or null)
// No try-catch needed!

Migration

Already using Hive, shared_preferences, or Riverpod? See docs/best-practices/migration.md for side-by-side comparisons.


Roadmap

Completed

  • x Phase 1: Memory Cache, TTL System, Basic Fetch Flow
  • x Phase 2: Cache Policies, Expiration Control, Stats System
  • x Phase 3: Request Deduplication, Stale While Revalidate
  • x Phase 4: Hive Persistent Storage, Two-Tier Architecture
  • x Phase 5: Encryption, Compression, Auth-Aware Caching
  • x Phase 6: Reactive Streams, CacheNexusBuilder Widget
  • x Phase 7: Offline Sync Queue, Background Retry

Planned

  • Phase 8: Dio/Retrofit Integration, Tag-Based Invalidation
  • Phase 9: Cache Warming, Prefetching, Background Refresh Scheduling
  • Phase 10: Full Dev Dashboard, Request Timeline, Analytics, Export Logs (JSON/CSV)
  • pub.dev publication

Contributing

Contributions are welcome! Here's how:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

See CONTRIBUTING.md for detailed development setup.


Contact

Platform Link
WhatsApp +972 59 804 5064
Email abdalftah.ps@gmail.com
LinkedIn Abd Alftah Salem

License

MIT License - see LICENSE for details.


Built with ❤️ for Flutter developers who care about performance, simplicity, and debugging clarity.

Libraries

cache_nexus
Offline-first, debuggable data orchestration layer for Flutter.