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.

69 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:farm_tpf/models/Supply.dart';
  6. import 'package:farm_tpf/utils/bloc/infinity_scroll_bloc.dart';
  7. import 'package:meta/meta.dart';
  8. part 'supply_event.dart';
  9. part 'supply_state.dart';
  10. class SupplyBloc extends Bloc<SupplyEvent, SupplyState> {
  11. final Repository repository;
  12. SupplyBloc({@required this.repository}) : super(SupplyInitial());
  13. @override
  14. Stream<SupplyState> mapEventToState(
  15. SupplyEvent event,
  16. ) async* {
  17. if (event is DataFetched) {
  18. try {
  19. final response = await repository.getSupplies(event.type);
  20. List<Supply> supplies = response.map((supply) {
  21. if (supply.id == event.selectedId) {
  22. supply.isSelected = true;
  23. }
  24. return supply;
  25. }).toList();
  26. yield SupplySuccess(items: supplies);
  27. } catch (_) {
  28. yield SupplyFailure();
  29. }
  30. } else if (event is OnRefresh) {
  31. try {
  32. final response = await repository.getSupplies(event.type);
  33. List<Supply> supplies = response.map((supply) {
  34. if (supply.id == event.selectedId) {
  35. supply.isSelected = true;
  36. }
  37. return supply;
  38. }).toList();
  39. yield SupplySuccess(items: supplies);
  40. } catch (_) {
  41. yield SupplyFailure();
  42. }
  43. } else if (event is OnSearch) {
  44. try {
  45. final response = await repository.getSupplies(event.type);
  46. bool query(Supply supply) =>
  47. event.searchString.isEmpty ||
  48. supply.name
  49. .toLowerCase()
  50. .contains(event.searchString.toLowerCase());
  51. final result = response.where(query).toList();
  52. List<Supply> supplies = result.map((supply) {
  53. if (supply.id == event.selectedId) {
  54. supply.isSelected = true;
  55. }
  56. return supply;
  57. }).toList();
  58. yield SupplySuccess(items: supplies);
  59. } catch (_) {
  60. yield SupplyFailure();
  61. }
  62. }
  63. }
  64. }