Core Query Prefetching
Prefetching improves user experience by loading data into the cache before it is needed.
Use the QueryClient to prefetch.
final client = QueryClient();
await client.prefetchQuery( 'todos'.toQueryKey(), () => fetchTodos(),);| Method | Description |
|---|---|
prefetchQuery(key, fn) | Fetches data and stores it in the cache. Does nothing if data is already fresh. |
Examples
Section titled “Examples”Prefetch on Hover
Section titled “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
Section titled “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
Section titled “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 oldclient.prefetchQuery( 'todos'.toQueryKey(), fetchTodos, options: QueryOptions(staleTime: Duration(minutes: 5)),);