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
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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
Which store
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
connectivity_plus tells you about an interface, not about reachability; treat request failures as the truth.Full example: offline-first cache snippet.