Mobile networks are unreliable by default: elevators, tunnels, weak signal, airplane mode. An app that shows a spinner and then an error whenever the connection drops feels broken. Offline-first flips the model: the app always works against local data, and syncing is a background concern.

I have used this approach for chat and booking-style features where a message or action must never be lost. Here is the pattern step by step.

The core idea

  1. The local database is the source of truth for the UI. Widgets read from it and never wait for the network.
  2. User actions are written to local storage first, together with a row in an outbox: a queue of changes that still have to reach the server.
  3. A sync worker drains the outbox when the network is available, and marks rows as done.
  4. Server changes are pulled and merged into the local database.

The outbox table

sql
CREATE TABLE outbox (
  id             INTEGER PRIMARY KEY AUTOINCREMENT,
  idempotency_key TEXT NOT NULL UNIQUE,
  type           TEXT NOT NULL,      -- 'send_message', 'create_booking', ...
  payload        TEXT NOT NULL,      -- JSON
  status         TEXT NOT NULL DEFAULT 'pending',  -- pending | sending | failed
  attempts       INTEGER NOT NULL DEFAULT 0,
  next_attempt_at INTEGER NOT NULL DEFAULT 0,
  created_at     INTEGER NOT NULL
);

Write locally and enqueue atomically

The domain change and the outbox row must succeed or fail together, so use one transaction:

dart
Future<void> sendMessage(String chatId, String text) async {
  final id = const Uuid().v4();
  await db.transaction((txn) async {
    await txn.insert('messages', {
      'id': id, 'chat_id': chatId, 'text': text,
      'state': 'pending', 'created_at': nowMs(),
    });
    await txn.insert('outbox', {
      'idempotency_key': id,
      'type': 'send_message',
      'payload': jsonEncode({'id': id, 'chat_id': chatId, 'text': text}),
      'created_at': nowMs(),
    });
  });
  unawaited(syncWorker.kick());
}

The UI shows the message instantly with a "pending" indicator. No loading screen, no lost input.

Drain the outbox safely

dart
Future<void> drain() async {
  final rows = await db.query('outbox',
      where: "status != 'sending' AND next_attempt_at <= ?",
      whereArgs: [nowMs()], orderBy: 'id', limit: 20);

  for (final row in rows) {
    await db.update('outbox', {'status': 'sending'}, where: 'id = ?', whereArgs: [row['id']]);
    try {
      await api.send(
        type: row['type'] as String,
        payload: jsonDecode(row['payload'] as String),
        idempotencyKey: row['idempotency_key'] as String,
      );
      await db.delete('outbox', where: 'id = ?', whereArgs: [row['id']]);
    } on DioException catch (e) {
      final attempts = (row['attempts'] as int) + 1;
      await db.update('outbox', {
        'status': isPermanent(e) ? 'failed' : 'pending',
        'attempts': attempts,
        'next_attempt_at': nowMs() + backoff(attempts).inMilliseconds,
      }, where: 'id = ?', whereArgs: [row['id']]);
    }
  }
}

Three details make this robust:

  • Idempotency keys. If the request succeeded but the response was lost, the retry would create a duplicate. Send the key in a header and have the server treat repeats as no-ops.
  • Backoff with a cap and jitter, for example min(2^attempts, 300) seconds plus random jitter, so thousands of clients do not retry in lockstep.
  • Permanent vs transient errors. A 400 will never succeed on retry; mark it failed and surface it. A timeout or 503 is retried.

When to run the worker

Do not poll blindly. Trigger a drain on:

  • app start and app resume,
  • connectivity changes (connectivity_plus),
  • right after an enqueue,
  • a periodic timer as a safety net (platform background-work APIs if you need it while the app is closed).

Note that connectivity status says a network interface is up, not that your server is reachable; the request result is the real signal.

Conflicts

If two devices edit the same record, you must decide who wins. Common strategies:

StrategyGood forTrade-off
Last write wins (server timestamp)Simple settings, profilesCan silently lose an edit
Version number, reject stale writesDocuments, bookingsNeeds a "reload and retry" UX
Append-only eventsChat, logsAlmost no conflicts, more storage

Pick per entity; chat messages are append-only, a profile is last-write-wins.

UI states that build trust

Show state, do not hide it: pending (clock icon), sent, failed with retry. Users forgive delay; they do not forgive silent loss.

Key takeaways

  • The local database drives the UI; the network is a background concern.
  • Write the change and its outbox row in one transaction.
  • Use idempotency keys, backoff with jitter, and separate permanent from transient failures.
  • Choose a conflict strategy per entity.

The same repository boundary from Clean Architecture is where this logic belongs, and the transport side is covered in building a resilient network layer. I design offline-capable mobile apps; get in touch if you need one.