DEV3 Technologies home

DEV3 Developer Forum

How should I cache API data for offline use in Flutter: SharedPreferences, Hive, Isar or SQLite?

Flutter helpSolved0 views
dev3 ·

My app shows products and orders from a REST API. I want it to open instantly and work without network. Which local storage should I use, and what pattern keeps the cache and server in sync?

#flutter#offline#sqlite#storage

0

1 reply

dev3 · Accepted answer

Which store

  • SharedPreferences: small settings and flags only (theme, onboarding done). Not for lists.
  • flutter_secure_storage: tokens and secrets (Keychain/Keystore).
  • SQLite via drift (or sqflite): best default for relational data, queries, pagination, migrations and reactive streams. Mature and stable.
  • Hive / Isar / ObjectBox: NoSQL object stores; fast and simple for key/value or document-like data. Check the maintenance status of the package at the time you choose, since several were slowed or forked.

For orders, products and anything you filter or sort, we recommend drift.

Pattern: cache first, then refresh (stale while revalidate)

Stream<List<Product>> watchProducts() async* {
  // 1. emit what we have immediately
  yield await db.productsDao.all();
  // 2. try the network
  try {
    final remote = await api.fetchProducts();
    await db.productsDao.replaceAll(remote);
  } catch (_) {
    // offline: keep showing the cache
  }
  // 3. keep emitting database changes
  yield* db.productsDao.watchAll();
}

The UI reads only from the database; the network only writes to it. This makes offline behaviour automatic.

Writes while offline

Queue them in a local pending_actions table (type, payload, created_at, attempt count). A sync worker (on app start, on connectivity change via connectivity_plus, and optionally workmanager for background) sends them in order and removes them on success. Give each action an idempotency key so retries do not duplicate orders.

Pitfalls

  • Plan schema migrations from day one.
  • Decide conflict rules (server wins, last write wins) explicitly.
  • connectivity_plus tells you about an interface, not about reachability; treat request failures as the truth.

Full example: offline-first cache snippet.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.