NetworkingMedium30 XP3 min read
How do you cache API responses locally in Flutter?
TL;DR: Cache API responses in Hive (NoSQL, fast) or Drift (SQLite, relational). Store the data with a TTL timestamp. On next request, check if cached data is fresh (<TTL). Return cache immediately, optionally refresh in the background.
Full Answer
Caching reduces network calls, speeds up perceived load time, and enables offline functionality. The key design decision is cache invalidation strategy.
Cache Strategies
- ▸Cache-first: Return cached data instantly, refresh in background (stale-while-revalidate)
- ▸Network-first: Always try network, fall back to cache on failure
- ▸Cache-only: Never hit network (offline mode toggle)
- ▸TTL-based: Cache is valid for N minutes, expired cache triggers fresh fetch
Code Examples
dartTTL-based cache with Hive
Output
// Within 30 min: instant return from Hive // After 30 min: fetch from API, update cache // No network: throws CacheExpiredException (handle gracefully)
Common Mistakes
- ✗Not storing cached_at timestamp — can't determine if cache is stale
- ✗Caching user-specific data globally — always include the user ID in the cache key
Interview Tip
💡
Describe stale-while-revalidate: show the cached data instantly, then refresh in the background and update the UI when fresh data arrives. Users see something immediately instead of a blank loading screen.
#caching#hive#shared-preferences#ttl#offline