posts_notifier.dart 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import 'package:flutter_riverpod/flutter_riverpod.dart';
  2. import 'package:veloe_kemono_party_flutter/kemono_client.dart';
  3. import 'package:veloe_kemono_party_flutter/models/post.dart';
  4. class PostsNotifier extends StateNotifier<AsyncValue<List<Post>>> {
  5. final String creatorId;
  6. final String service;
  7. final String query;
  8. final KemonoClient client;
  9. int _currentPage = 0;
  10. bool _reachedEnd = false;
  11. PostsNotifier({
  12. required this.creatorId,
  13. required this.service,
  14. required this.query,
  15. required this.client,
  16. }) : super(const AsyncValue.loading()) {
  17. loadInitial();
  18. }
  19. Future<void> loadInitial() async {
  20. if (!mounted) return;
  21. state = const AsyncValue.loading();
  22. try {
  23. final posts = await client.getPosts(
  24. creatorId,
  25. service,
  26. _currentPage * 50,
  27. query
  28. );
  29. state = AsyncValue.data(posts);
  30. _currentPage = 1;
  31. } catch (e) {
  32. state = AsyncValue.error(e, StackTrace.current);
  33. }
  34. }
  35. Future<void> loadNext() async {
  36. if (!mounted ||state.isLoading || _reachedEnd) return;
  37. final previousPosts = state.valueOrNull ?? [];
  38. state = AsyncValue<List<Post>>.loading().copyWithPrevious(state);
  39. try {
  40. final newPosts = await client.getPosts(
  41. creatorId,
  42. service,
  43. _currentPage * 50,
  44. query
  45. );
  46. if (newPosts.length == 0){
  47. _reachedEnd = true;
  48. return;
  49. }
  50. state = AsyncValue.data([...previousPosts, ...newPosts]);
  51. _currentPage++;
  52. } catch (e) {
  53. state = AsyncValue<List<Post>>.error(e, StackTrace.current)
  54. .copyWithPrevious(AsyncValue.data(previousPosts));
  55. }
  56. }
  57. }