♻️ Refactor riverpod pagination loading
This commit is contained in:
@ -12,10 +12,12 @@ import 'package:island/models/post.dart';
|
||||
import 'package:island/widgets/check_in.dart';
|
||||
import 'package:island/widgets/post/post_item.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:very_good_infinite_list/very_good_infinite_list.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:riverpod_paging_utils/riverpod_paging_utils.dart';
|
||||
import 'package:island/pods/network.dart';
|
||||
|
||||
part 'explore.g.dart';
|
||||
|
||||
@RoutePage()
|
||||
class ExploreScreen extends ConsumerWidget {
|
||||
const ExploreScreen({super.key});
|
||||
@ -23,8 +25,7 @@ class ExploreScreen extends ConsumerWidget {
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final user = ref.watch(userInfoProvider);
|
||||
final posts = ref.watch(activityListProvider);
|
||||
final postsNotifier = ref.watch(activityListProvider.notifier);
|
||||
final activitiesNotifier = ref.watch(activityListNotifierProvider.notifier);
|
||||
|
||||
return AppScaffold(
|
||||
appBar: AppBar(title: const Text('explore').tr()),
|
||||
@ -33,7 +34,7 @@ class ExploreScreen extends ConsumerWidget {
|
||||
onPressed: () {
|
||||
context.router.push(PostComposeRoute()).then((value) {
|
||||
if (value != null) {
|
||||
ref.invalidate(activityListProvider);
|
||||
activitiesNotifier.forceRefresh();
|
||||
}
|
||||
});
|
||||
},
|
||||
@ -41,108 +42,110 @@ class ExploreScreen extends ConsumerWidget {
|
||||
),
|
||||
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () => postsNotifier.refresh(),
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
if (user.hasValue) SliverToBoxAdapter(child: CheckInWidget()),
|
||||
SliverInfiniteList(
|
||||
itemCount: posts.length,
|
||||
isLoading: postsNotifier.isLoading,
|
||||
hasReachedMax: postsNotifier.hasReachedMax,
|
||||
onFetchData: postsNotifier.fetchMore,
|
||||
itemBuilder: (context, index) {
|
||||
final item = posts[index];
|
||||
switch (item.type) {
|
||||
case 'posts.new':
|
||||
return PostItem(
|
||||
item: SnPost.fromJson(item.data),
|
||||
onRefresh: (_) {
|
||||
ref.invalidate(activityListProvider);
|
||||
},
|
||||
onUpdate: (post) {
|
||||
postsNotifier.updateOne(
|
||||
index,
|
||||
item.copyWith(data: post.toJson()),
|
||||
);
|
||||
},
|
||||
);
|
||||
case 'accounts.check-in':
|
||||
return CheckInActivityWidget(item: item);
|
||||
case 'accounts.status':
|
||||
return StatusActivityWidget(item: item);
|
||||
default:
|
||||
return Placeholder();
|
||||
}
|
||||
},
|
||||
separatorBuilder: (_, __) => const Divider(height: 1),
|
||||
),
|
||||
SliverGap(MediaQuery.of(context).padding.bottom + 16),
|
||||
],
|
||||
onRefresh: () => Future.sync(activitiesNotifier.forceRefresh),
|
||||
child: PagingHelperView(
|
||||
provider: activityListNotifierProvider,
|
||||
futureRefreshable: activityListNotifierProvider.future,
|
||||
notifierRefreshable: activityListNotifierProvider.notifier,
|
||||
contentBuilder:
|
||||
(data, widgetCount, endItemView) => CustomScrollView(
|
||||
slivers: [
|
||||
if (user.hasValue) SliverToBoxAdapter(child: CheckInWidget()),
|
||||
SliverList.builder(
|
||||
itemCount: widgetCount,
|
||||
itemBuilder: (context, index) {
|
||||
if (index == widgetCount - 1) {
|
||||
return endItemView;
|
||||
}
|
||||
|
||||
final item = data.items[index];
|
||||
Widget itemWidget;
|
||||
|
||||
switch (item.type) {
|
||||
case 'posts.new':
|
||||
itemWidget = PostItem(
|
||||
item: SnPost.fromJson(item.data),
|
||||
onRefresh: (_) {
|
||||
activitiesNotifier.forceRefresh();
|
||||
},
|
||||
onUpdate: (post) {
|
||||
activitiesNotifier.updateOne(
|
||||
index,
|
||||
item.copyWith(data: post.toJson()),
|
||||
);
|
||||
},
|
||||
);
|
||||
break;
|
||||
case 'accounts.check-in':
|
||||
itemWidget = CheckInActivityWidget(item: item);
|
||||
break;
|
||||
case 'accounts.status':
|
||||
itemWidget = StatusActivityWidget(item: item);
|
||||
break;
|
||||
default:
|
||||
itemWidget = const Placeholder();
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [itemWidget, const Divider(height: 1)],
|
||||
);
|
||||
},
|
||||
),
|
||||
SliverGap(MediaQuery.of(context).padding.bottom + 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final activityListProvider =
|
||||
StateNotifierProvider<_ActivityListController, List<SnActivity>>((ref) {
|
||||
final client = ref.watch(apiClientProvider);
|
||||
return _ActivityListController(client);
|
||||
});
|
||||
@riverpod
|
||||
class ActivityListNotifier extends _$ActivityListNotifier
|
||||
with CursorPagingNotifierMixin<SnActivity> {
|
||||
@override
|
||||
Future<CursorPagingData<SnActivity>> build() => fetch(cursor: null);
|
||||
|
||||
class _ActivityListController extends StateNotifier<List<SnActivity>> {
|
||||
_ActivityListController(this._dio) : super([]);
|
||||
@override
|
||||
Future<CursorPagingData<SnActivity>> fetch({required String? cursor}) async {
|
||||
final client = ref.read(apiClientProvider);
|
||||
final offset = cursor == null ? 0 : int.parse(cursor);
|
||||
final take = 20;
|
||||
|
||||
final Dio _dio;
|
||||
bool isLoading = false;
|
||||
bool hasReachedMax = false;
|
||||
int offset = 0;
|
||||
final int take = 20;
|
||||
int total = 0;
|
||||
final response = await client.get(
|
||||
'/activities',
|
||||
queryParameters: {'offset': offset, 'take': take},
|
||||
);
|
||||
|
||||
Future<void> fetchMore() async {
|
||||
if (isLoading || hasReachedMax) return;
|
||||
isLoading = true;
|
||||
final List<SnActivity> items =
|
||||
(response.data as List)
|
||||
.map((e) => SnActivity.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
'/activities',
|
||||
queryParameters: {'offset': offset, 'take': take},
|
||||
);
|
||||
final total = int.tryParse(response.headers['x-total']?.first ?? '') ?? 0;
|
||||
final hasMore = offset + items.length < total;
|
||||
final nextCursor = hasMore ? (offset + items.length).toString() : null;
|
||||
|
||||
final List<SnActivity> fetched =
|
||||
(response.data as List)
|
||||
.map((e) => SnActivity.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
final headerTotal = int.tryParse(
|
||||
response.headers['x-total']?.first ?? '',
|
||||
);
|
||||
if (headerTotal != null) total = headerTotal;
|
||||
|
||||
if (!mounted) return; // Check if the notifier is still mounted
|
||||
|
||||
state = [...state, ...fetched];
|
||||
offset += fetched.length;
|
||||
if (state.length >= total) hasReachedMax = true;
|
||||
} finally {
|
||||
if (mounted) {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
return CursorPagingData(
|
||||
items: items,
|
||||
hasMore: hasMore,
|
||||
nextCursor: nextCursor,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> refresh() async {
|
||||
offset = 0;
|
||||
state = [];
|
||||
hasReachedMax = false;
|
||||
await fetchMore();
|
||||
}
|
||||
void updateOne(int index, SnActivity activity) {
|
||||
final currentState = state.valueOrNull;
|
||||
if (currentState == null) return;
|
||||
|
||||
void updateOne(int index, SnActivity post) {
|
||||
if (!mounted) return; // Check if the notifier is still mounted
|
||||
final updatedPosts = [...state];
|
||||
updatedPosts[index] = post;
|
||||
state = updatedPosts;
|
||||
final updatedItems = [...currentState.items];
|
||||
updatedItems[index] = activity;
|
||||
|
||||
state = AsyncData(
|
||||
CursorPagingData(
|
||||
items: updatedItems,
|
||||
hasMore: currentState.hasMore,
|
||||
nextCursor: currentState.nextCursor,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user