-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathpaged_notifier.dart
75 lines (67 loc) · 2.75 KB
/
paged_notifier.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_infinite_scroll/src/paged_notifier_mixin.dart';
import 'package:riverpod_infinite_scroll/src/paged_state.dart';
typedef LoadFunction<PageKeyType, ItemType> = Future<List<ItemType>?> Function(
PageKeyType page, int limit);
typedef NextPageKeyBuilder<PageKeyType, ItemType> = PageKeyType? Function(
List<ItemType>? lastItems, PageKeyType page, int limit);
/// A [StateNotifier] that has already all the properties that `riverpod_infinite_scroll` needs and is intended for simple states only containing a list of `records`
class PagedNotifier<PageKeyType, ItemType>
extends StateNotifier<PagedState<PageKeyType, ItemType>>
with
PagedNotifierMixin<PageKeyType, ItemType,
PagedState<PageKeyType, ItemType>> {
/// Load function
final LoadFunction<PageKeyType, ItemType> _load;
/// Instructs the class on how to build the next page based on the last answer
final NextPageKeyBuilder<PageKeyType, ItemType> nextPageKeyBuilder;
/// A builder for providing a custom error string
final dynamic Function(dynamic error)? errorBuilder;
/// A builder for providing a custom error string
final bool printStackTrace;
PagedNotifier(
{required LoadFunction<PageKeyType, ItemType> load,
required this.nextPageKeyBuilder,
this.errorBuilder,
this.printStackTrace = false})
: _load = load,
super(PagedState<PageKeyType, ItemType>());
@override
Future<List<ItemType>?> load(PageKeyType page, int limit) async {
// avoid repeated call to the same page
if (state.previousPageKeys.contains(page)) {
await Future.delayed(const Duration(seconds: 0), () {
state = state.copyWith();
});
return state.records;
}
try {
final records = await _load(page, limit);
state = state.copyWith(
records: [
...(state.records ?? <ItemType>[]),
...(records ?? <ItemType>[])
],
nextPageKey: nextPageKeyBuilder(records, page, limit),
previousPageKeys: {...state.previousPageKeys, page}.toList());
return records;
} catch (e, stacktrace) {
if (mounted) {
state = state.copyWith(
error: errorBuilder != null
? errorBuilder!(e)
: 'An error occurred. Please try again.');
debugPrint(e.toString());
if (printStackTrace) { debugPrint(stacktrace.toString()); }
}
}
return null;
}
}
class NextPageKeyBuilderDefault<ItemType> {
static NextPageKeyBuilder<int, dynamic> mysqlPagination =
(List<dynamic>? lastItems, int page, int limit) {
return (lastItems == null || lastItems.length < limit) ? null : (page + 1);
};
}