Skip to Content

Infinite Queries

Infinite queries allow you to handle paginated data, such as “Load More” lists or infinite scrolls.

Usage

Since Fasq currently provides the raw logic for infinite queries, you can use it with a standard StreamBuilder.

// 1. Define the fetch function Future<List<Post>> fetchPosts(int page) async { return api.getPosts(page: page); } // 2. Create the InfiniteQuery final query = QueryClient().getInfiniteQuery<List<Post>, int>( 'posts'.toQueryKey(), (page) => fetchPosts(page), options: InfiniteQueryOptions( // Define how to get the next page param getNextPageParam: (pages, lastPage) { return pages.length; // Simple page number logic }, ), ); // 3. Use standard StreamBuilder class PostList extends StatefulWidget { @override _PostListState createState() => _PostListState(); } class _PostListState extends State<PostList> { @override void initState() { super.initState(); // Start listening to data query.addListener(); // Fetch first page if needed if (query.state.pages.isEmpty) { query.fetchNextPage(0); } } @override void dispose() { query.removeListener(); super.dispose(); } @override Widget build(BuildContext context) { return StreamBuilder( stream: query.stream, initialData: query.state, builder: (context, snapshot) { final state = snapshot.data!; // Flatten pages into a single list final posts = state.pages.expand((page) => page.data ?? []).toList(); return ListView.builder( itemCount: posts.length + 1, itemBuilder: (context, index) { if (index == posts.length) { // Load more button return ElevatedButton( onPressed: state.isFetchingNextPage ? null : () => query.fetchNextPage(), child: state.isFetchingNextPage ? const CircularProgressIndicator() : const Text('Load More'), ); } return ListTile(title: Text(posts[index].title)); }, ); }, ); } }

API

InfiniteQueryOptions

PropertyDescription
getNextPageParamFunction to calculate the next page parameter given the current pages. Return null to indicate no more pages.
getPreviousPageParamFunction to calculate the previous page parameter.
maxPagesMaximum number of pages to keep in memory (auto-garbage collection for lists).

InfiniteQueryState

PropertyDescription
pagesList of Page<TData, TParam> objects containing your data.
hasNextPageBoolean indicating if there is more data to fetch.
isFetchingNextPageTrue if currently fetching the next page.
Last updated on