D
ArchitectureHard50 XP4 min read

How do you design an offline-first architecture in Flutter?

TL;DR: Offline-first means the local database is the single source of truth. Writes go to local DB first, then sync to the server. Reads always come from local DB, which is hydrated by background sync. Use Hive or Drift for local storage.

Full Answer

Architecture Flow

  • App starts: Read from local DB immediately (fast, no flicker)
  • Background sync: Fetch latest data from API, update local DB
  • User writes: Save to local DB, queue for sync, optimistically update UI
  • Online detected: Flush write queue to server, handle conflicts

Storage Options

  • Hive: NoSQL key-value, fast, lightweight, great for settings and simple objects
  • Drift (formerly moor): SQLite with type-safe Dart queries, reactive streams, relations
  • Isar: Fast NoSQL with full-text search, ideal for complex queries
  • flutter_secure_storage: Encrypted key-value for sensitive data (tokens)
🎯

Drift's watchSingleOrNull() returns a Stream that emits whenever the DB row changes. Combine with BlocProvider or Riverpod's StreamProvider for reactive offline-first UI.

Code Examples

dartOffline-first repository with Drift
Output
// User sees data instantly (from local DB)
// UI refreshes silently when API response arrives

Common Mistakes

  • Showing loading spinners when local data is available — offline-first should feel instantaneous
  • Not handling sync conflicts — define a conflict resolution strategy (last-write-wins, server-wins)

Interview Tip

💡

Offline-first is the difference between apps that work at 0 bars and apps that show spinners. Show you understand the local-first read + background sync + optimistic write pattern.

#offline-first#hive#drift#sync#cache