Building Resilient Offline-First Flutter Apps: The Repository Pattern & Cache Synchronization
Modern users expect mobile applications to launch instantly, display recently accessed data offline in airplane mode, and allow seamless interactions regardless of intermittent cellular connectivity.
Treating network connectivity as a guaranteed prerequisite leads to broken user flows, spinner fatigue, and poor app store ratings. In this technical guide, we architect a resilient Offline-First Synchronization Engine in Flutter.
1. The Offline-First User Expectation {#the-offline-first-mandate}
In traditional "network-first" architectures:
- The user opens the app.
- The UI renders a blocking spinner.
- The app issues an HTTP request.
- If the connection times out or fails, an error dialog is presented.
In an Offline-First (Local-First) architecture:
- The user opens the app.
- The UI immediately hydrates from local persistent disk storage (0ms wait time).
- A background task checks for network availability and queries the remote server for differential updates.
- When fresh data arrives, the local store updates and notifies reactive UI listeners to smoothly morph state.
2. Choosing Local Storage: SQLite vs Isar vs Hive {#local-first-storage-engines}
| Engine | Storage Type | Query Capabilities | Performance Profile | Ideal Use Case |
|---|---|---|---|---|
| SQLite (Drift) | Relational SQL | Joins, Indexes, Full ACID | Extremely fast for structured datasets | Complex relational models, financial ledgers |
| Isar | NoSQL Object Store | Static typings, Composite Indexes | Ultra-fast native memory mapping | High-volume offline logs, feed caching |
| Hive | Key-Value Store | Key lookups, basic indexing | Fast startup, low footprint | User settings, auth tokens, small payloads |
3. The Cache-Then-Network Strategy {#cache-then-network-pattern}
The canonical implementation of the Repository Pattern with a cache-then-network strategy exposes a reactive Stream that emits twice: first with cached disk state, and second with remote server updates.
import 'dart:async';
class BookmarkRepositoryImpl implements BookmarkRepository {
final LocalBookmarkDatabase _localDb;
final RemoteBookmarkApi _remoteApi;
BookmarkRepositoryImpl(this._localDb, this._remoteApi);
@override
Stream<List<Bookmark>> watchBookmarks() async* {
// 1. Instantly yield cached data from local database
final cached = await _localDb.getAllBookmarks();
if (cached.isNotEmpty) {
yield cached.map((m) => m.toEntity()).toList();
}
// 2. Fetch latest changes from remote server in background
try {
final remoteData = await _remoteApi.fetchBookmarks();
// 3. Update local cache (Single Source of Truth)
await _localDb.syncBookmarks(remoteData);
// 4. Emit the updated data set
yield remoteData.map((m) => m.toEntity()).toList();
} catch (error) {
// In offline conditions, the user continues uninterrupted with the cached state!
if (cached.isEmpty) {
throw OfflineException('No cached data available offline.');
}
}
}
}
4. Queuing Offline Mutations with Background Sync {#offline-mutation-queues}
When a user triggers an action offline (such as favoriting a lesson or completing a quiz), the application must not display an error message. Instead, it should:
- Optimistically update the local database: The UI updates instantaneously.
- Enqueue the mutation into an offline task queue: Persisted to SQLite or Hive.
- Listen for connectivity restoration: When cellular or Wi-Fi connectivity returns (via the
connectivity_pluspackage), the background queue flushes pending actions chronologically to the backend API.
5. Handling Sync Conflicts in Distributed Mobile Systems {#conflict-resolution}
When data can be edited both offline on a mobile device and remotely on web dashboards, conflict resolution strategies must be defined:
- Last-Write-Wins (LWW): Relies on synchronized NTP timestamps. Simplest, but vulnerable to clock drift.
- Server Authority: The remote server rejects modifications if the client's
updatedAtversion precedes the server's current version hash. - Field-Level Differential Merging: Only conflicting fields prompt manual user reconciliation; independent fields merge seamlessly.