You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.1KB

  1. import 'dart:async';
  2. import 'package:bloc/bloc.dart';
  3. import 'package:equatable/equatable.dart';
  4. import 'package:farm_tpf/data/repository/repository.dart';
  5. import 'package:meta/meta.dart';
  6. part 'infinity_scroll_event.dart';
  7. part 'infinity_scroll_state.dart';
  8. class InfinityScrollBloc
  9. extends Bloc<InfinityScrollEvent, InfinityScrollState> {
  10. final Repository repository;
  11. InfinityScrollBloc({@required this.repository})
  12. : super(InfinityScrollInitial());
  13. static int pageSize = 20;
  14. @override
  15. Stream<InfinityScrollState> mapEventToState(
  16. InfinityScrollEvent event,
  17. ) async* {
  18. if (event is DataFetched &&
  19. !(state is InfinityScrollSuccess &&
  20. (state as InfinityScrollSuccess).hasReachedMax)) {
  21. try {
  22. if (state is InfinityScrollInitial) {
  23. final response =
  24. await repository.getInfinityList("url", page: 0, size: pageSize);
  25. yield InfinityScrollSuccess(
  26. items: response.results,
  27. page: 0,
  28. hasReachedMax: response.results.length < pageSize ? true : false);
  29. }
  30. if (state is InfinityScrollSuccess) {
  31. final currentState = state as InfinityScrollSuccess;
  32. int page = currentState.page + 1;
  33. final response = await repository.getInfinityList("url",
  34. page: page, size: pageSize);
  35. yield response.results.isEmpty
  36. ? currentState.copyWith(hasReachedMax: true)
  37. : InfinityScrollSuccess(
  38. items: currentState.items + response.results,
  39. page: currentState.page + 1,
  40. hasReachedMax: false);
  41. }
  42. } catch (e) {
  43. print(e);
  44. yield InfinityScrollFailure();
  45. }
  46. }
  47. if (event is OnRefresh) {
  48. try {
  49. final response =
  50. await repository.getInfinityList("url", page: 0, size: pageSize);
  51. yield InfinityScrollSuccess(
  52. items: response.results,
  53. page: 0,
  54. hasReachedMax: response.results.length < pageSize ? true : false);
  55. } catch (_) {
  56. yield InfinityScrollFailure();
  57. }
  58. }
  59. }
  60. }