posts_notifier.dart 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. PostsNotifier({
  11. required this.creatorId,
  12. required this.service,
  13. required this.query,
  14. required this.client,
  15. }) : super(const AsyncValue.loading()) {
  16. loadInitial();
  17. }
  18. Future<void> loadInitial() async {
  19. if (!mounted) return;
  20. state = const AsyncValue.loading();
  21. try {
  22. final posts = await client.getPosts(
  23. creatorId,
  24. service,
  25. _currentPage * 50,
  26. query
  27. );
  28. state = AsyncValue.data(posts);
  29. _currentPage = 1;
  30. } catch (e) {
  31. state = AsyncValue.error(e, StackTrace.current);
  32. }
  33. }
  34. Future<void> loadNext() async {
  35. if (!mounted ||state.isLoading) return;
  36. final previousPosts = state.valueOrNull ?? [];
  37. state = AsyncValue<List<Post>>.loading().copyWithPrevious(state);
  38. try {
  39. final newPosts = await client.getPosts(
  40. creatorId,
  41. service,
  42. _currentPage * 50,
  43. query
  44. );
  45. state = AsyncValue.data([...previousPosts, ...newPosts]);
  46. _currentPage++;
  47. } catch (e) {
  48. state = AsyncValue<List<Post>>.error(e, StackTrace.current)
  49. .copyWithPrevious(AsyncValue.data(previousPosts));
  50. }
  51. }
  52. }