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.

68 lines
2.0KB

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