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.

76 lines
2.5KB

  1. import 'dart:async';
  2. import 'package:bloc/bloc.dart';
  3. import 'package:equatable/equatable.dart';
  4. import 'package:farm_tpf/data/api/app_exception.dart';
  5. import 'package:farm_tpf/data/repository/repository.dart';
  6. import 'package:meta/meta.dart';
  7. part 'plot_event.dart';
  8. part 'plot_state.dart';
  9. class PlotBloc extends Bloc<PlotEvent, PlotState> {
  10. final Repository repository;
  11. PlotBloc({@required this.repository}) : super(PlotInitial());
  12. static int pageSize = 20;
  13. @override
  14. Stream<PlotState> mapEventToState(
  15. PlotEvent event,
  16. ) async* {
  17. if (event is DataFetched &&
  18. !(state is PlotSuccess && (state as PlotSuccess).hasReachedMax)) {
  19. try {
  20. if (state is PlotInitial) {
  21. yield PlotLoading();
  22. final response = await repository.getPlots(page: 0, size: pageSize);
  23. yield PlotSuccess(
  24. items: response,
  25. page: 0,
  26. hasReachedMax: response.length < pageSize ? true : false);
  27. }
  28. if (state is PlotSuccess) {
  29. final currentState = state as PlotSuccess;
  30. int page = currentState.page + 1;
  31. yield PlotLoading();
  32. final response =
  33. await repository.getPlots(page: page, size: pageSize);
  34. yield response.isEmpty
  35. ? currentState.copyWith(hasReachedMax: true)
  36. : PlotSuccess(
  37. items: currentState.items + response,
  38. page: currentState.page + 1,
  39. hasReachedMax: false);
  40. }
  41. } catch (e) {
  42. var errorString = AppException.handleError(e);
  43. yield PlotFailure(errorString: errorString);
  44. }
  45. }
  46. if (event is OnRefresh) {
  47. try {
  48. yield PlotLoading();
  49. final response = await repository.getPlots(page: 0, size: pageSize);
  50. yield PlotSuccess(
  51. items: response,
  52. page: 0,
  53. hasReachedMax: response.length < pageSize ? true : false);
  54. } catch (e) {
  55. yield PlotFailure(errorString: AppException.handleError(e));
  56. }
  57. } else if (event is OnSearch) {
  58. try {
  59. yield PlotLoading();
  60. final response = await repository.getPlots(
  61. page: 0, size: pageSize, searchString: event.searchString);
  62. yield PlotSuccess(
  63. items: response,
  64. page: 0,
  65. hasReachedMax: response.length < pageSize ? true : false);
  66. } catch (e) {
  67. yield PlotFailure(errorString: AppException.handleError(e));
  68. }
  69. }
  70. }
  71. }