Skip to content

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(),
);
MethodDescription
prefetchQuery(key, fn)Fetches data and stores it in the cache. Does nothing if data is already fresh.

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'),
)

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)));
}

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)),
);