Prefetching
Prefetching improves user experience by loading data into the cache before it is needed.
Usage
Use the QueryClient to prefetch.
final client = QueryClient();
await client.prefetchQuery(
'todos'.toQueryKey(),
() => fetchTodos(),
);API
| Method | Description |
|---|---|
prefetchQuery(key, fn) | Fetches data and stores it in the cache. Does nothing if data is already fresh. |
Examples
Prefetch on Hover
On the web, or for specific interactions, prefetching can make navigation feel instant.
InkWell(
onHover: (hovering) {
if (hovering) {
QueryClient().prefetchQuery('profile'.toQueryKey(), fetchProfile);
}
},
onTap: () => Navigator.pushNamed(context, '/profile'),
child: Text('Go to Profile'),
)Prefetch for Next Screen
Call prefetch before pushing a new route.
void goToDetails(String id) {
// Start fetching now
QueryClient().prefetchQuery('details:$id'.toQueryKey(), () => fetchDetails(id));
// Navigate
Navigator.push(context, MaterialPageRoute(builder: (_) => DetailsPage(id)));
}Staleness
Prefetching respects staleTime. If the data is already in cache and fresh, prefetchQuery will not trigger a network request.
// Won't refetch if data is < 5 mins old
client.prefetchQuery(
'todos'.toQueryKey(),
fetchTodos,
options: QueryOptions(staleTime: Duration(minutes: 5)),
);Last updated on