Offline - Offline-First Architecture
Implement offline-first architecture with local storage, automatic sync, and conflict resolution. Supports multiple patterns from fully offline apps to online-first with offline fallback.
When to Use This Skill
- Adding offline support to existing features
- Building fully offline-first apps
- Implementing data synchronization
- Adding local caching with sync
- User asks "offline mode", "sync data", "work offline", "cache locally"
When NOT to Use This Skill
- Simple in-memory caching - Use
/data caching patterns instead
- Network connectivity detection - Use
/network-connectivity instead
- Error handling for failed requests - Use
/data NetworkFailure types
Questions to Ask
- Offline mode: Fully offline-first or online-first with offline fallback?
- Data complexity: Simple key-value or structured relational data?
- Sync strategy: Periodic sync, on-demand, or push-based?
- Conflict resolution: Last-write-wins, server-wins, or custom merge?
- Data sensitivity: Does local data need encryption?
Quick Reference
Offline Patterns
| Pattern |
Use When |
Local DB |
Sync |
| Fully Offline |
Notes, journals, todo apps |
Primary |
Optional upload |
| Offline-First |
Field apps, travel apps |
Primary |
Background sync |
| Online-First + Fallback |
E-commerce, social apps |
Cache |
On reconnect |
| Cache-Only |
Read-heavy feeds |
TTL cache |
Refresh on pull |
Storage Options
| Storage |
Best For |
Encryption |
Performance |
| Drift (SQLite) |
Relational data, complex queries |
AES-256 via SQLCipher |
Fast |
| Hive |
Key-value, settings, small objects |
Built-in AES-256 |
Very fast |
| Isar |
Large datasets, full-text search |
Limited |
Fastest |
| SharedPreferences |
Flags, simple settings |
None |
Fast |
| SecureStorage |
Tokens, PII |
Platform keychain |
Slower |
Sync Strategies
| Strategy |
Trigger |
Best For |
| Periodic |
Timer (5-15 min) |
Background updates |
| On-Demand |
User pull-to-refresh |
User-controlled sync |
| On-Reconnect |
Connectivity change |
Offline queue flush |
| Push-Based |
FCM/WebSocket |
Real-time apps |
| Delta Sync |
Timestamp-based |
Large datasets |
Conflict Resolution
| Strategy |
How It Works |
Best For |
| Last-Write-Wins (LWW) |
Latest timestamp wins |
Simple apps, non-critical data |
| Server-Wins |
Server always authoritative |
Multi-user shared data |
| Client-Wins |
Local changes preserved |
Single-user apps |
| Custom Merge |
Field-level merge logic |
Complex business rules |
| User Prompt |
Ask user to resolve |
Important conflicts |
Workflow
Phase 1: Analyze Requirements
- Determine offline pattern (see Quick Reference)
- Identify data that needs offline access
- Choose storage solution based on data complexity
- Define sync strategy and conflict resolution
Phase 2: Setup Local Storage
- Add dependencies to
pubspec.yaml
- Create local database models/tables
- Implement local data source
See: storage-guide.md for detailed setup
Phase 3: Implement Sync Layer
- Add sync status tracking to models
- Create sync queue for pending operations
- Implement sync service with conflict resolution
- Add background sync via WorkManager (optional)
See: sync-guide.md for sync patterns
Phase 4: Update Repository
- Modify repository to read local-first
- Add write-through or write-behind patterns
- Handle sync status in domain entities
- Integrate with connectivity monitoring
Phase 5: Verify
dart run .claude/skills/offline/scripts/check.dart --feature {feature}
Core API
final items = await repository.getAll(); // Local-first read
await repository.create(item); // Saves locally, queues sync
final isSynced = ref.watch(syncStatusProvider);
See: storage-guide.md for dependencies and file structure.
Guides
| File |
Content |
| architecture-guide.md |
Offline architecture patterns and decisions |
| storage-guide.md |
Local storage setup (Drift, Hive) |
| sync-guide.md |
Sync strategies and conflict resolution |
Reference Files
See: reference/ for complete implementations:
reference/models/ - SyncStatus enum, SyncOperation, OfflineEntity mixin
reference/local_storage/ - Drift database, Hive local source
reference/sync/ - SyncQueue, SyncService, ConflictResolver
reference/repositories/ - Offline-first and cache-first patterns
reference/providers/ - Sync status providers
Checklist
Setup:
Models:
Repository:
Sync:
Verification:
Related Skills
/network-connectivity - Connectivity monitoring and offline banner
/data - Base repository patterns, caching, error handling
/push-notifications - Push-based sync triggers
/analytics - Track sync events and failures
Common Issues
| Issue |
Solution |
| Data not persisting |
Ensure database initialized before use (await AppDatabase.init()) |
| Sync queue grows indefinitely |
Implement retry limits and age-based pruning |
| Conflicts overwriting local |
Use timestamps for LWW, or user prompts for critical data |
| Slow startup on large datasets |
Use pagination, lazy-load details on demand |
See: sync-guide.md for detailed troubleshooting.
Next Steps
After running this skill:
- Run
/network-connectivity for offline banner
- Run
/testing for offline scenario tests
- Run
/i18n for sync status messages
- Consider
/push-notifications for push-based sync
1---2name: offline3description: Offline-first architecture with local storage, sync, and conflict resolution. Use when adding offline support, data synchronization, local caching, or queue-based sync. Supports fully offline apps and online-first apps with offline fallback.4---56# Offline - Offline-First Architecture78Implement offline-first architecture with local storage, automatic sync, and conflict resolution. Supports multiple patterns from fully offline apps to online-first with offline fallback.910## When to Use This Skill1112- Adding offline support to existing features13- Building fully offline-first apps14- Implementing data synchronization15- Adding local caching with sync16- User asks "offline mode", "sync data", "work offline", "cache locally"1718## When NOT to Use This Skill1920- **Simple in-memory caching** - Use `/data` caching patterns instead21- **Network connectivity detection** - Use `/network-connectivity` instead22- **Error handling for failed requests** - Use `/data` NetworkFailure types2324## Questions to Ask25261. **Offline mode:** Fully offline-first or online-first with offline fallback?272. **Data complexity:** Simple key-value or structured relational data?283. **Sync strategy:** Periodic sync, on-demand, or push-based?294. **Conflict resolution:** Last-write-wins, server-wins, or custom merge?305. **Data sensitivity:** Does local data need encryption?3132## Quick Reference3334### Offline Patterns3536| Pattern | Use When | Local DB | Sync |37|---------|----------|----------|------|38| **Fully Offline** | Notes, journals, todo apps | Primary | Optional upload |39| **Offline-First** | Field apps, travel apps | Primary | Background sync |40| **Online-First + Fallback** | E-commerce, social apps | Cache | On reconnect |41| **Cache-Only** | Read-heavy feeds | TTL cache | Refresh on pull |4243### Storage Options4445| Storage | Best For | Encryption | Performance |46|---------|----------|------------|-------------|47| **Drift (SQLite)** | Relational data, complex queries | AES-256 via SQLCipher | Fast |48| **Hive** | Key-value, settings, small objects | Built-in AES-256 | Very fast |49| **Isar** | Large datasets, full-text search | Limited | Fastest |50| **SharedPreferences** | Flags, simple settings | None | Fast |51| **SecureStorage** | Tokens, PII | Platform keychain | Slower |5253### Sync Strategies5455| Strategy | Trigger | Best For |56|----------|---------|----------|57| **Periodic** | Timer (5-15 min) | Background updates |58| **On-Demand** | User pull-to-refresh | User-controlled sync |59| **On-Reconnect** | Connectivity change | Offline queue flush |60| **Push-Based** | FCM/WebSocket | Real-time apps |61| **Delta Sync** | Timestamp-based | Large datasets |6263### Conflict Resolution6465| Strategy | How It Works | Best For |66|----------|--------------|----------|67| **Last-Write-Wins (LWW)** | Latest timestamp wins | Simple apps, non-critical data |68| **Server-Wins** | Server always authoritative | Multi-user shared data |69| **Client-Wins** | Local changes preserved | Single-user apps |70| **Custom Merge** | Field-level merge logic | Complex business rules |71| **User Prompt** | Ask user to resolve | Important conflicts |7273## Workflow7475### Phase 1: Analyze Requirements76771. Determine offline pattern (see Quick Reference)782. Identify data that needs offline access793. Choose storage solution based on data complexity804. Define sync strategy and conflict resolution8182### Phase 2: Setup Local Storage83841. Add dependencies to `pubspec.yaml`852. Create local database models/tables863. Implement local data source8788**See:** [storage-guide.md](storage-guide.md) for detailed setup8990### Phase 3: Implement Sync Layer91921. Add sync status tracking to models932. Create sync queue for pending operations943. Implement sync service with conflict resolution954. Add background sync via WorkManager (optional)9697**See:** [sync-guide.md](sync-guide.md) for sync patterns9899### Phase 4: Update Repository1001011. Modify repository to read local-first1022. Add write-through or write-behind patterns1033. Handle sync status in domain entities1044. Integrate with connectivity monitoring105106### Phase 5: Verify107108```bash109dart run .claude/skills/offline/scripts/check.dart --feature {feature}110```111112## Core API113114```dart115final items = await repository.getAll(); // Local-first read116await repository.create(item); // Saves locally, queues sync117final isSynced = ref.watch(syncStatusProvider);118```119120**See:** [storage-guide.md](storage-guide.md) for dependencies and file structure.121122## Guides123124| File | Content |125|------|---------|126| [architecture-guide.md](architecture-guide.md) | Offline architecture patterns and decisions |127| [storage-guide.md](storage-guide.md) | Local storage setup (Drift, Hive) |128| [sync-guide.md](sync-guide.md) | Sync strategies and conflict resolution |129130## Reference Files131132**See:** `reference/` for complete implementations:133134- `reference/models/` - SyncStatus enum, SyncOperation, OfflineEntity mixin135- `reference/local_storage/` - Drift database, Hive local source136- `reference/sync/` - SyncQueue, SyncService, ConflictResolver137- `reference/repositories/` - Offline-first and cache-first patterns138- `reference/providers/` - Sync status providers139140## Checklist141142**Setup:**143- [ ] Offline pattern determined (fully offline vs. online-first + fallback)144- [ ] Storage solution chosen (Drift/Hive) and added to pubspec.yaml145- [ ] Local database/tables created146147**Models:**148- [ ] Domain entity has `syncStatus` field149- [ ] DTO model has sync tracking fields (`localId`, `updatedAt`, `isSynced`)150- [ ] Client-generated UUIDs for new entities151152**Repository:**153- [ ] Reads from local storage first154- [ ] Writes to local storage immediately155- [ ] Queues remote sync operations156- [ ] Handles sync failures gracefully157158**Sync:**159- [ ] Sync queue persists pending operations160- [ ] Sync triggers on connectivity restore161- [ ] Conflict resolution strategy implemented162- [ ] Sync status exposed to UI163164**Verification:**165- [ ] Works in airplane mode166- [ ] Data persists across app restarts167- [ ] Sync completes when online168- [ ] Conflicts resolved correctly169170## Related Skills171172- `/network-connectivity` - Connectivity monitoring and offline banner173- `/data` - Base repository patterns, caching, error handling174- `/push-notifications` - Push-based sync triggers175- `/analytics` - Track sync events and failures176177## Common Issues178179| Issue | Solution |180|-------|----------|181| Data not persisting | Ensure database initialized before use (`await AppDatabase.init()`) |182| Sync queue grows indefinitely | Implement retry limits and age-based pruning |183| Conflicts overwriting local | Use timestamps for LWW, or user prompts for critical data |184| Slow startup on large datasets | Use pagination, lazy-load details on demand |185186**See:** [sync-guide.md](sync-guide.md) for detailed troubleshooting.187188## Next Steps189190After running this skill:1911. Run `/network-connectivity` for offline banner1922. Run `/testing` for offline scenario tests1933. Run `/i18n` for sync status messages1944. Consider `/push-notifications` for push-based sync