docs: add infinite query page
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
---
|
||||
title: Infinite Queries
|
||||
sidebar_position: 11
|
||||
---
|
||||
|
||||
|
||||
Rendering lists that can additively "load more" data onto an existing set of data or "infinite scroll" is also a very common UI pattern. Fl Query supports a useful version of `Query` called `InfiniteQuery` for querying these types of lists.
|
||||
|
||||
When using `InfiniteQueryBuilder`, you'll notice a few things are different:
|
||||
|
||||
- `data` is now an object containing infinite query data as `Map<type of page parameter, type of page data>`
|
||||
- `data.pages` List containing the fetched pages
|
||||
- `data.pageParams` List containing the page params used to fetch the pages
|
||||
- The `fetchNextPage` and `fetchPreviousPage` methods are now available
|
||||
- The `getNextPageParam` and `getPreviousPageParam` options are available for both determining if there is more data to load and the information to fetch it. This information is supplied as an additional parameter in the query function (which can optionally be overridden when calling the `fetchNextPage` or `fetchPreviousPage` methods)
|
||||
- A `hasNextPage` boolean is now available and is `true` if `getNextPageParam` returns a value other than `false`
|
||||
- A `hasPreviousPage` boolean is now available and is `true` if `getPreviousPageParam` returns a value other than `false`
|
||||
- The `isFetchingNextPage` and `isFetchingPreviousPage` booleans are now available to distinguish between a background refresh state and a loading more state
|
||||
|
||||
|
||||
## Example
|
||||
|
||||
Let's assume we have an API that returns pages of `projects` 3 at a time based on a `cursor` index along with a cursor that can be used to fetch the next group of projects:
|
||||
|
||||
```dart
|
||||
http.get('$hostUrl/api/projects?cursor=0');
|
||||
// { data: [...], nextCursor: 3}
|
||||
http.get('$hostUrl/api/projects?cursor=3');
|
||||
// { data: [...], nextCursor: 6}
|
||||
http.get('$hostUrl/api/projects?cursor=6');
|
||||
// { data: [...], nextCursor: 9}
|
||||
http.get('$hostUrl/api/projects?cursor=9');
|
||||
// { data: [...] }
|
||||
```
|
||||
|
||||
With this information, we can create a "Load More" UI by:
|
||||
|
||||
- Waiting for `InfiniteQuery` to request the first group of data by default
|
||||
- Returning the information for the next query in `getNextPageParam`
|
||||
- Calling `fetchNextPage` function
|
||||
|
||||
> Note: It's very important you do not call `fetchNextPage` with arguments unless you want them to override the `pageParam` data returned from the `getNextPageParam` function
|
||||
|
||||
```dart
|
||||
import "packages:fl_query/fl_query.dart";
|
||||
import "package:http/http.dart" as http;
|
||||
|
||||
final projectsJob = InfiniteQueryJob<Map<String, dynamic>, void, int>(
|
||||
queryKey: 'projects',
|
||||
initialParam: 0,
|
||||
getNextPageParam: (lastPage, pages) => lastPage['nextCursor'],
|
||||
getPreviousPageParam: (currentPage, pages) => currentPage['previousCursor'],
|
||||
task: (queryKey, pageParam, externalData){
|
||||
return http.get('$hostUrl/api/projects?cursor=$pageParam');
|
||||
},
|
||||
);
|
||||
|
||||
class Projects extends StatelessWidget{
|
||||
Project({super.key});
|
||||
|
||||
@override
|
||||
build(context){
|
||||
return InfiniteQueryBuilder(
|
||||
job: projectsJob,
|
||||
builder: (context, query){
|
||||
if(query.isLoading){
|
||||
return Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if(query.isError){
|
||||
return Center(child: Text('Error: ${query.error}'));
|
||||
}
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
ListView.builder(
|
||||
itemCount: query.pages.length,
|
||||
itemBuilder: (context, index){
|
||||
final project = query.pages[index];
|
||||
return ListTile(title: Text(project['name']));
|
||||
}
|
||||
),
|
||||
Align(
|
||||
alignment: Alignment.bottomRight,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.get_app_rounded),
|
||||
onPressed: query.isFetchingNextPage || !query.hasNextPage
|
||||
? null
|
||||
: () => query.fetchNextPage(),
|
||||
),
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## What happens when an infinite query needs to be refetched?
|
||||
|
||||
When an infinite query becomes `stale` and needs to be refetched, each group is fetched `sequentially`, starting from the first one. This ensures that even if the underlying data is mutated, we're not using stale cursors and potentially getting duplicates or skipping records. If an infinite query's results are ever removed from the QueryBowl's Cache, the pagination restarts at the initial state with only the initial group being requested.
|
||||
|
||||
### refetchPage
|
||||
|
||||
If you only want to actively refetch a subset of all pages, you can use the `refetchPage` method of `InfiniteQuery`. It optionally takes a `selector callback` to programmatically choose which pages to refetch. If no selector is provided, all pages will be refetched sequentially.
|
||||
|
||||
```dart
|
||||
// refetching all the pages
|
||||
infiniteQuery.refetchPages();
|
||||
|
||||
// refetching custom selected pages
|
||||
infiniteQuery.refetchPages((page, pageParam, allPages){
|
||||
// this will refetch all the pages that are fetched after the 10th page
|
||||
return pageParam > 10;
|
||||
})
|
||||
```
|
||||
|
||||
## What if I need to pass custom page parameter to my `fetchNextPage` function?
|
||||
|
||||
By default, the variable returned from `getNextPageParam` will be supplied to the task function, but in some cases, you may want to override this. You can pass custom `getNextPageParam` to the `fetchNextPage` method only for that very call which will override the default variable like so:
|
||||
|
||||
```dart
|
||||
infiniteQuery.fetchNextPage((lastPage, lastParam)=> 20)
|
||||
```
|
||||
|
||||
|
||||
## Manually update the infinite query data
|
||||
|
||||
Manually removing first page:
|
||||
|
||||
```dart
|
||||
QueryBowl.of(context)
|
||||
.setQueryData(exampleInfiniteQueryJob.queryKey, (oldData){
|
||||
oldData?.remove(0);
|
||||
return Map.from(oldData ?? {});
|
||||
})
|
||||
```
|
||||
|
||||
Manually removing a single value from an individual page:
|
||||
|
||||
```dart
|
||||
QueryBowl.of(context)
|
||||
.setQueryData(exampleInfiniteQueryJob.queryKey, (oldData){
|
||||
oldData?.removeWhere((key, value){
|
||||
return value["id"] != someOtherValue["id"];
|
||||
});
|
||||
return Map.from(oldData ?? {});
|
||||
})
|
||||
```
|
||||
|
||||
## Infinite Query with Dynamic queryKey
|
||||
|
||||
Just like regular [`QueryJob`](/docs/basics/DynamicQueries), `InfiniteQueryJob` also supports dynamic queryKeys via the `InfiniteQuery.withVariableKey` static method. This is useful when your API/source of data returns the same structure of data for multiple endpoints e.g dynamic routes.
|
||||
|
||||
```dart
|
||||
final projectsJob = InfiniteQueryJob.withVariableKey<Map<String, dynamic>, void, int>(
|
||||
queryKey: (queryKey) => 'projects-$queryKey',
|
||||
initialParam: 0,
|
||||
getNextPageParam: (lastPage, pages) => lastPage['nextCursor'],
|
||||
getPreviousPageParam: (currentPage, pages) => currentPage['previousCursor'],
|
||||
task: (queryKey, pageParam, externalData){
|
||||
final projectId = getVariable(queryKey);
|
||||
return http.get('$hostUrl/api/projects/$projectId/?cursor=$pageParam');
|
||||
},
|
||||
);
|
||||
|
||||
// using the same query function for multiple queries
|
||||
InfiniteQueryBuilder(
|
||||
job: projectsJob.withQueryKey('1'),
|
||||
builder: (context, query){
|
||||
// ...
|
||||
}
|
||||
)
|
||||
|
||||
InfiniteQueryBuilder(
|
||||
job: projectsJob.withQueryKey('2'),
|
||||
builder: (context, query){
|
||||
// ...
|
||||
}
|
||||
)
|
||||
```
|
||||
@@ -1 +1 @@
|
||||
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"connectivity_plus","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus-2.3.6/","native_build":true,"dependencies":[]}],"android":[{"name":"connectivity_plus","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus-2.3.6/","native_build":true,"dependencies":[]}],"macos":[{"name":"connectivity_plus_macos","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_macos-1.2.4/","native_build":true,"dependencies":[]}],"linux":[{"name":"connectivity_plus_linux","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_linux-1.3.1/","native_build":false,"dependencies":[]}],"windows":[{"name":"connectivity_plus_windows","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_windows-1.2.2/","native_build":true,"dependencies":[]}],"web":[{"name":"connectivity_plus_web","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_web-1.2.3/","dependencies":[]}]},"dependencyGraph":[{"name":"connectivity_plus","dependencies":["connectivity_plus_linux","connectivity_plus_macos","connectivity_plus_web","connectivity_plus_windows"]},{"name":"connectivity_plus_linux","dependencies":[]},{"name":"connectivity_plus_macos","dependencies":[]},{"name":"connectivity_plus_web","dependencies":[]},{"name":"connectivity_plus_windows","dependencies":[]}],"date_created":"2022-09-15 12:05:12.417424","version":"3.3.0"}
|
||||
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"connectivity_plus","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus-2.3.6/","native_build":true,"dependencies":[]}],"android":[{"name":"connectivity_plus","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus-2.3.6/","native_build":true,"dependencies":[]}],"macos":[{"name":"connectivity_plus_macos","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_macos-1.2.4/","native_build":true,"dependencies":[]}],"linux":[{"name":"connectivity_plus_linux","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_linux-1.3.1/","native_build":false,"dependencies":[]}],"windows":[{"name":"connectivity_plus_windows","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_windows-1.2.2/","native_build":true,"dependencies":[]}],"web":[{"name":"connectivity_plus_web","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_web-1.2.3/","dependencies":[]}]},"dependencyGraph":[{"name":"connectivity_plus","dependencies":["connectivity_plus_linux","connectivity_plus_macos","connectivity_plus_web","connectivity_plus_windows"]},{"name":"connectivity_plus_linux","dependencies":[]},{"name":"connectivity_plus_macos","dependencies":[]},{"name":"connectivity_plus_web","dependencies":[]},{"name":"connectivity_plus_windows","dependencies":[]}],"date_created":"2022-09-19 10:39:45.071010","version":"3.3.0"}
|
||||
@@ -37,9 +37,36 @@ class BasicInfiniteQueryExample extends StatelessWidget {
|
||||
return Stack(
|
||||
children: [
|
||||
ListView.builder(
|
||||
itemCount: infiniteQuery.pages.length,
|
||||
itemCount: infiniteQuery.pages.length + 1,
|
||||
itemBuilder: (context, index) {
|
||||
final page = infiniteQuery.pages[index];
|
||||
if (index == 0) {
|
||||
return Text(
|
||||
"""
|
||||
InfiniteQuery properties
|
||||
|
||||
isFetchingNextPage: ${infiniteQuery.isFetchingNextPage}
|
||||
isFetchingPreviousPage: ${infiniteQuery.isFetchingPreviousPage}
|
||||
isLoading: ${infiniteQuery.isLoading}
|
||||
isRefetching: ${infiniteQuery.isRefetching}
|
||||
isError: ${infiniteQuery.isError}
|
||||
isSuccess: ${infiniteQuery.isSuccess}
|
||||
isIdle: ${infiniteQuery.isIdle}
|
||||
isInactive: ${infiniteQuery.isInactive}
|
||||
isStale: ${infiniteQuery.isStale}
|
||||
fetched: ${infiniteQuery.fetched}
|
||||
|
||||
hasData: ${infiniteQuery.hasData}
|
||||
hasError: ${infiniteQuery.hasError}
|
||||
hasNextPage: ${infiniteQuery.hasNextPage}
|
||||
hasPreviousPage: ${infiniteQuery.hasPreviousPage}
|
||||
|
||||
refetchCount: ${infiniteQuery.refetchCount}
|
||||
retryAttempts: ${infiniteQuery.retryAttempts}
|
||||
updatedAt: ${infiniteQuery.updatedAt}
|
||||
""",
|
||||
);
|
||||
}
|
||||
final page = infiniteQuery.pages[index - 1];
|
||||
return ListTile(
|
||||
title: Text(page?["title"] ?? ""),
|
||||
subtitle: Text(page?["body"] ?? ""),
|
||||
|
||||
@@ -29,8 +29,8 @@ class InfiniteQuery<T extends Object, Outside, PageParam extends Object>
|
||||
InfiniteQueryPageParamFunction<T, PageParam>? getNextPageParam;
|
||||
InfiniteQueryPageParamFunction<T, PageParam>? getPreviousPageParam;
|
||||
|
||||
bool _hasNextPage = false;
|
||||
bool _hasPreviousPage = false;
|
||||
bool _hasNextPage = true;
|
||||
bool _hasPreviousPage = true;
|
||||
|
||||
bool _isFetchingNextPage = false;
|
||||
bool _isFetchingPreviousPage = false;
|
||||
@@ -184,7 +184,7 @@ class InfiniteQuery<T extends Object, Outside, PageParam extends Object>
|
||||
}
|
||||
|
||||
Future<List<T>> refetchPages([
|
||||
bool Function(T? page, int index, List<T?> allPages)? selector,
|
||||
bool Function(T? page, PageParam pageParam, List<T?> allPages)? selector,
|
||||
]) async {
|
||||
if (isFetchingNextPage ||
|
||||
isFetchingPreviousPage ||
|
||||
@@ -194,7 +194,7 @@ class InfiniteQuery<T extends Object, Outside, PageParam extends Object>
|
||||
final queue = Queue();
|
||||
for (final entry in data?.entries.toList() ?? <MapEntry<PageParam, T?>>[]) {
|
||||
final page = entry.value;
|
||||
final selected = selector?.call(page, pages.indexOf(page), pages) ?? true;
|
||||
final selected = selector?.call(page, entry.key, pages) ?? true;
|
||||
if (!selected) continue;
|
||||
_currentParam = entry.key;
|
||||
queue.add<void>(
|
||||
|
||||
@@ -40,9 +40,36 @@ class BasicHookInfiniteQueryExample extends HookWidget {
|
||||
body: Stack(
|
||||
children: [
|
||||
ListView.builder(
|
||||
itemCount: infiniteQuery.pages.length,
|
||||
itemCount: infiniteQuery.pages.length + 1,
|
||||
itemBuilder: (context, index) {
|
||||
final page = infiniteQuery.pages[index];
|
||||
if (index == 0) {
|
||||
return Text(
|
||||
"""
|
||||
InfiniteQuery properties
|
||||
|
||||
isFetchingNextPage: ${infiniteQuery.isFetchingNextPage}
|
||||
isFetchingPreviousPage: ${infiniteQuery.isFetchingPreviousPage}
|
||||
isLoading: ${infiniteQuery.isLoading}
|
||||
isRefetching: ${infiniteQuery.isRefetching}
|
||||
isError: ${infiniteQuery.isError}
|
||||
isSuccess: ${infiniteQuery.isSuccess}
|
||||
isIdle: ${infiniteQuery.isIdle}
|
||||
isInactive: ${infiniteQuery.isInactive}
|
||||
isStale: ${infiniteQuery.isStale}
|
||||
fetched: ${infiniteQuery.fetched}
|
||||
|
||||
hasData: ${infiniteQuery.hasData}
|
||||
hasError: ${infiniteQuery.hasError}
|
||||
hasNextPage: ${infiniteQuery.hasNextPage}
|
||||
hasPreviousPage: ${infiniteQuery.hasPreviousPage}
|
||||
|
||||
refetchCount: ${infiniteQuery.refetchCount}
|
||||
retryAttempts: ${infiniteQuery.retryAttempts}
|
||||
updatedAt: ${infiniteQuery.updatedAt}
|
||||
""",
|
||||
);
|
||||
}
|
||||
final page = infiniteQuery.pages[index - 1];
|
||||
return ListTile(
|
||||
title: Text(page?["title"] ?? ""),
|
||||
subtitle: Text(page?["body"] ?? ""),
|
||||
|
||||
Reference in New Issue
Block a user