posts_notifier.dart 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 KemonoClient client;
  8. int _currentPage = 0;
  9. PostsNotifier({
  10. required this.creatorId,
  11. required this.service,
  12. required this.client,
  13. }) : super(const AsyncValue.loading()) {
  14. loadInitial();
  15. }
  16. Future<void> loadInitial() async {
  17. state = const AsyncValue.loading();
  18. try {
  19. final posts = await client.getPosts(creatorId, service, 0);
  20. state = AsyncValue.data(posts);
  21. _currentPage = 1;
  22. } catch (e) {
  23. state = AsyncValue.error(e, StackTrace.current);
  24. }
  25. }
  26. Future<void> loadNext() async {
  27. if (state.isLoading) return;
  28. final previousPosts = state.valueOrNull ?? [];
  29. // Add explicit type parameter
  30. state = AsyncValue<List<Post>>.loading().copyWithPrevious(state);
  31. try {
  32. final newPosts = await client.getPosts(
  33. creatorId,
  34. service,
  35. _currentPage * 50
  36. );
  37. print('Loading page $_currentPage with offset ${_currentPage * 20}');
  38. state = AsyncValue.data([...previousPosts, ...newPosts]);
  39. _currentPage++;
  40. } catch (e) {
  41. // Specify type for error state
  42. state = AsyncValue<List<Post>>.error(e, StackTrace.current)
  43. .copyWithPrevious(AsyncValue.data(previousPosts));
  44. }
  45. }
  46. }