Networking 11 min read Updated 2026-03-15

Building Resilient Offline-First Flutter Apps: The Repository Pattern & Cache Synchronization

Architecting robust offline-first mobile experiences. Discover how to synchronize remote REST/GraphQL APIs with local databases, manage offline write queues, and resolve data conflicts gracefully.

FC

FlutterCraft Engineering Editorial

Staff Editorial

Staff Mobile Architects and Core Maintainers specializing in large-scale cross-platform Flutter engineering.

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:

  1. The user opens the app.
  2. The UI renders a blocking spinner.
  3. The app issues an HTTP request.
  4. If the connection times out or fails, an error dialog is presented.

In an Offline-First (Local-First) architecture:

  1. The user opens the app.
  2. The UI immediately hydrates from local persistent disk storage (0ms wait time).
  3. A background task checks for network availability and queries the remote server for differential updates.
  4. 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}

EngineStorage TypeQuery CapabilitiesPerformance ProfileIdeal Use Case
SQLite (Drift)Relational SQLJoins, Indexes, Full ACIDExtremely fast for structured datasetsComplex relational models, financial ledgers
IsarNoSQL Object StoreStatic typings, Composite IndexesUltra-fast native memory mappingHigh-volume offline logs, feed caching
HiveKey-Value StoreKey lookups, basic indexingFast startup, low footprintUser 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:

  1. Optimistically update the local database: The UI updates instantaneously.
  2. Enqueue the mutation into an offline task queue: Persisted to SQLite or Hive.
  3. Listen for connectivity restoration: When cellular or Wi-Fi connectivity returns (via the connectivity_plus package), 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 updatedAt version precedes the server's current version hash.
  • Field-Level Differential Merging: Only conflicting fields prompt manual user reconciliation; independent fields merge seamlessly.