Riverpod-Implementierung von infinite_scroll_pagination, dieses Paket ermöglicht die Verwendung von infinite_scroll_pagination mit Riverpod und verdeckt die Komplexität
Aus öffentlichen Paketdaten erstellte Orientierung.
Riverpod_infinite_scroll ist ein Flutter-Paket, das eine Riverpod-basierte Implementierung der unendlichen Scroll-Pagination bereitstellt und die Integration von unendlichem Scrollen mit der Riverpod-Zustandsverwaltung vereinfacht. Es versteckt die Komplexität des Managements von paginierten Datenströmen und erleichtert die Erstellung effizienter, skalierbarer Listenansichten, die Daten schrittweise laden, während Benutzer scrollen. Für Entwickler, die Riverpod verwenden, entwickelt, sorgt es für sauberen, testbaren Code mit minimalem Boilerplate. Das Paket ermöglicht nahtlose Integration in bestehende Riverpod-Architekturen und steigert die Produktivität durch automatische Behandlung von Zustandsübergängen und Lade-Logik.
Anwendungsfälle
Unendliche Listen in Flutter-Apps erstellen
Verzögerter Ladevorgang für große Datensätze implementieren
Glatte Benutzererlebnisse mit dynamischem Inhalt erstellen
Pagination mit Riverpod-Zustandsverwaltung integrieren
Komplexe Scroll-Logik in datenintensiven Benutzeroberflächen vereinfachen
Hauptmerkmale
Zustandsverwaltung mit Riverpod
Automatisches Paginierungsmanagement
Minimale Boilerplate-Code
Nahtlose Integration mit Riverpod-Anbietern
Unterstützt Ladezustände und Fehlerbehandlung
Geeignet für
Flutter-Entwickler, die Riverpod verwenden
Anwendungen mit großen oder dynamisch geladenen Listen
Teams, die sauberen, wartbaren Code priorisieren
Entwickler, die eine vereinfachte Paginierungslogik suchen
Projekte, die bei der Scrollfunktion einen effizienten Speichereinsatz erfordern
Hinweise
Benötigt Riverpod-Abhängigkeit
Beschränkt auf Flutter-Plattformen
Möglicherweise ist eine benutzerdefinierte Konfiguration für komplexe Paginierungslogik erforderlich
Nicht geeignet für nicht scrollbare paginierte Daten
Abhängig vom Upstream-Paket infinite_scroll_pagination
Original-README
Originaler README-Schnappschuss aus dem verknüpften Quell-Repository. Aktuelle Inhalte finden Sie im Repository.
This StateNotifierProvider must implement two methods to ensure everything works correctly, it must have a load method, and a nextPageKeyBuilder method, these will be explained below.
riverpod_infinite_scroll ensures our StateNotifier will respect these constraints with the choice of two classes:
You can either use the simple:
PagedNotifier - You can create a class that extends PagedNotifier a notifier that has all the properties that riverpod_infinite_scroll needs and is intended for simple states only containing a list of records
Or if you need more flexbility to handle a more complex state object you can use a StateNotifier that uses PagedState (or a state that extends PagedState) - in such case a mixin that ensures your StateNotifier will implement the load method with the correct types is provided with PagedNotifierMixin
Example - Simple version
Let's see an example now! We have an API that returns a list of Post objects, this API is paginated and we need to show a feed displaying those Posts.
The widget we will use for displaying such a feed is RiverPagedBuilder!. Refer to source code: easy_example.dart
As we can see RiverPagedBuilder is small and easy to implement with the following properties:
firstPageKey - the first page we sent to our paginated API
provider - The StateNotifierProvider that holds the logic and the list of Posts
itemBuilder - a function that builds a single Post
pagedBuilder - The type of list we want to render. This can be any of the infinite_scroll_pagination widgets, and this package already gives us the PaginationController and the BuilderDelegate
classEasyExampleNotifierextendsPagedNotifier<int, Post> {
EasyExampleNotifier():
super(
//load is a required method of PagedNotifier
load: (page, limit) => Future.delayed(constDuration(seconds: 2), () {
// This simulates a network call to an api that returns paginated postsreturn [
constPost(id: 1, title: "My first work", image: "https://www.mywebsite.com/image1"),
constPost(id: 2, title: "My second work", image: "https://www.mywebsite.com/image2"),
constPost(id: 3, title: "My third work", image: "https://www.mywebsite.com/image3"),
];
}),
//nextPageKeyBuilder is a required method of PagedNotifier
nextPageKeyBuilder: NextPageKeyBuilderDefault.mysqlPagination,
);
// Example of custom methods you are free to implement in StateNotifiervoidadd(Post post) {
state = state.copyWith(records: [ ...(state.records ?? []), post ]);
}
voiddelete(Post post) {
state = state.copyWith(records: [ ...(state.records ?? []) ]..remove(post));
}
}
//create a global provider as you would normally in riverpod:final easyExampleProvider = StateNotifierProvider<EasyExampleNotifier, PagedState<int, Post>>((_) => EasyExampleNotifier());
We can extend PagedNotifier which is a child of StateNotifier and everything will be done for us.
PagedNotifier only asks for a load function, and a nextPageKeyBuilder function that returns the next page. and that's it!
In the example above we used NextPageKeyBuilderDefault.mysqlPagination , a default function to reduce boilerplate.
Also notice the records member of the internal state object of PagedNotifier is accessible and modifiable in the standard Riverpod way through this custom function add
voidadd(Post post) {
state = state.copyWith(records: [ ...(state.records ?? []), post ]);
}
A more custom example
If you need to keep track of a more complex state than a simple list of recordsRiverpod Infinite Scroll also provides a more customizable approach.
Let's suppose we need to fetch from a paginated API that return a list of users. Source code: (custom_example.dart)[https://github.com/ftognetto/riverpod_infinite_scroll/blob/main/example/lib/custom/custom_example.dart]
We have used a PagedGridView here instead of a PagedListView only to make things more fun. This package works with any of the infinite_scroll_pagination widgets.
Now let's have a look of how we can create a more custom StateNotifier, first a simple class to represent a User:
And we have the StateNotifier that manages those users. Source code: (custom_example_provider.dart)[https://github.com/ftognetto/riverpod_infinite_scroll/blob/main/example/lib/custom/custom_example_provider.dart]
classCustomExampleNotifierextendsStateNotifier<CustomExampleState>
withPagedNotifierMixin<String, User, CustomExampleState> {
CustomExampleNotifier() : super(constCustomExampleState());
@overrideFuture<List<User>?> load(String page, int limit) async {
try {
//as build can be called many times, ensure//we only hit our page API once per pageif (state.previousPageKeys.contains(page)) {
awaitFuture.delayed(constDuration(seconds: 0), () {
state = state.copyWith();
});
return state.records;
}
var users = awaitFuture.delayed(constDuration(seconds: 3), () {
// This simulates a network call to an api that returns paginated usersreturn [
constUser(
id: "abcdef",
name: "John",
profilePicture: "https://www.mywebsite.com/images/1"),
constUser(
id: "asdfgh",
name: "Mary",
profilePicture: "https://www.mywebsite.com/images/2"),
constUser(
id: "qwerty",
name: "Robert",
profilePicture: "https://www.mywebsite.com/images/3")
];
});
// we then update state accordingly
state = state.copyWith(records: [
...(state.records ?? []),
...users
], nextPageKey: users.length < limit ? null : users[users.length - 1].id,
previousPageKeys: {...state.previousPageKeys, page}.toList());
} catch (e) {
// in case of error we should notifiy the listeners
state = state.copyWith(error: e.toString());
}
}
// Super simple example of custom methods of the StateNotifiervoidadd(User user) {
state = state.copyWith(records: [...(state.records ?? []), user]);
}
voiddelete(User user) {
state = state.copyWith(records: [...(state.records ?? [])]..remove(user));
}
}
final customExampleProvider =
StateNotifierProvider<CustomExampleNotifier, CustomExampleState>(
(_) => CustomExampleNotifier());
We didn't use PagedNotifier, instead we used a normal Riverpod StateNotifier with the PagedNotifierMixin which ensures the notifier has a correctly typed load method.
Let's take a closer look at :
Future<List<User>?> load(String page, int limit) async {
Where does this String page get set? Well some of you may have noticed this firstPageKey whatever string is in there will be passed to the page argument of load:
and then just change the Generics of load and RiverPagedBuilder and your state object that extends PagedState to match.
Custom wrapper for loading/error/try again states
The RiverPagedBuilder offers, other than the properties we already saw, the same properties that infinite_scroll_pagination offers.
firstPageProgressIndicatorBuilder - a builder for the loading state in the first call
newPageProgressIndicatorBuilder - a builder for the loading state for the subsequent requests
firstPageErrorIndicatorBuilder - a builder for the error state in the first call
newPageErrorIndicatorBuilder - a builder for the error state for the subsequent requests
noItemsFoundIndicatorBuilder - a builder for the empty state in the first call
noMoreItemsIndicatorBuilder - a builder for the empty state for the subsequent request (we have fetched all the items!)
If we need to give a coherent design to our app we could wrap the RiverPagedBuilder into a new Widget!
Testing
An integration test is provided demonstrating how easy it is to test this widget:
https://github.com/ftognetto/riverpod_infinite_scroll/blob/main/example/integration_test/app_test.dart