Stale Time & Refetching
Understanding the distinction between stale data and cached data is essential to mastering fquery_core:
cacheDuration: How long inactive data stays in memory before being garbage collected.staleDuration: How long data is considered "fresh" before an observer treats it as "stale" and eligible for a background refetch.
Fresh vs Stale
When a query resolves successfully, its dataUpdatedAt timestamp is recorded.
dart
final isStale = query.dataUpdatedAt
?.add(staleDuration)
.isBefore(DateTime.now()) ?? true;- While Fresh (
now < dataUpdatedAt + staleDuration): If an observer mounts or requests data, it returns cached data immediately without triggering a network request. - When Stale (
now >= dataUpdatedAt + staleDuration): Cached data is still returned immediately (so the UI never flickers with empty loading spinners), but a background refetch is initiated.
Refetch Policies (refetchOnMount)
You can customize how an observer behaves on mount:
dart
enum RefetchOnMount {
/// Always refetch in the background on mount, even if data is fresh.
always,
/// Refetch only if the data is stale (default).
stale,
/// Never refetch on mount if data already exists in cache.
never,
}Periodic Polling (refetchInterval)
For real-time data that updates frequently on the server (e.g. stock prices, sports scores, chat notifications), configure a refetchInterval:
dart
final observer = QueryObserver(
cache: cache,
queryKey: QueryKey(['prices']),
queryFn: fetchStockPrices,
refetchInterval: Duration(seconds: 10), // refetches every 10 seconds
);To stop polling dynamically:
dart
observer.updateOptions(
QueryOptions(
queryKey: observer.queryKey,
queryFn: observer.queryFn,
refetchInterval: null, // cancels interval timer
),
);