All articles
9 min read
November 14, 20269 min read

Building Offline-First Flutter Apps with Local Caching and Sync Engines

Architect robust mobile apps that work completely offline using Isar database, write-ahead sync queues, and conflict resolution strategies.

Tags:#Flutter#Offline-First#Isar#Database
Building Offline-First Flutter Apps with Local Caching and Sync Engines

Mobile connections are inherently unreliable. A well-engineered mobile application should treat offline availability not as an edge case, but as the default operational state.

In this article, we break down the architecture of a production-tested Offline-First Sync Engine in Flutter.


1. The Core Architectural Philosophy

An offline-first architecture rests on three pillars:

  1. Single Source of Truth: The UI reads exclusively from the local database (e.g., Isar or Drift). It never waits for an API response to render.
  2. Write-Ahead Sync Queue: User actions mutate local storage immediately and enqueue a pending mutation task in a persistent queue.
  3. Background Sync Worker: A dedicated background worker continuously flushes queued mutations to the server whenever internet connectivity is restored.

2. Implementing the Mutation Queue

dart
@collection
class SyncTask {
  Id id = Isar.autoIncrement;
  late String endpoint;
  late String httpMethod; // POST, PUT, DELETE
  late String payloadJson;
  late DateTime createdAt;
  int retryCount = 0;
}

class SyncEngine {
  final Isar isar;
  final ApiClient api;

  SyncEngine(this.isar, this.api);

  Future<void> flushQueue() async {
    final pendingTasks = await isar.syncTasks
        .where()
        .sortByCreatedAt()
        .findAll();

    for (final task in pendingTasks) {
      try {
        await api.execute(task.endpoint, task.httpMethod, task.payloadJson);
        await isar.writeTxn(() => isar.syncTasks.delete(task.id));
      } catch (e) {
        task.retryCount++;
        await isar.writeTxn(() => isar.syncTasks.put(task));
        break; // Stop execution on network error to preserve sequential order
      }
    }
  }
}

3. Conflict Resolution Strategies

  • Client-Wins (Last Write Wins): Suitable for user profile updates and individual preference toggles.
  • Server-Wins: Best for inventory reservation and collaborative document edits.
  • CRDTs (Conflict-free Replicated Data Types): Ideal for chat applications and collaborative lists.