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.

72 lines
2.3KB

  1. import 'dart:async';
  2. import 'package:bloc/bloc.dart';
  3. import 'package:equatable/equatable.dart';
  4. import 'package:farm_tpf/custom_model/LocationUnit.dart';
  5. import 'package:farm_tpf/data/repository/repository.dart';
  6. import 'package:farm_tpf/utils/const_common.dart';
  7. import 'package:meta/meta.dart';
  8. part 'location_event.dart';
  9. part 'location_state.dart';
  10. class LocationBloc extends Bloc<LocationEvent, LocationState> {
  11. final Repository repository;
  12. LocationBloc({@required this.repository}) : super(LocationInitial());
  13. @override
  14. Stream<LocationState> mapEventToState(
  15. LocationEvent event,
  16. ) async* {
  17. if (event is DataFetched) {
  18. try {
  19. final response = await repository.getLocationUnits(
  20. locationType: event.locationType, filterId: event.filterId);
  21. List<LocationUnit> locations = response.map((location) {
  22. if (location.id == event.selectedId) {
  23. location.isSelected = true;
  24. }
  25. return location;
  26. }).toList();
  27. yield LocationSuccess(items: locations);
  28. } catch (_) {
  29. yield LocationFailure();
  30. }
  31. } else if (event is OnRefresh) {
  32. try {
  33. final response = await repository.getLocationUnits(
  34. locationType: event.locationType, filterId: event.filterId);
  35. List<LocationUnit> locations = response.map((location) {
  36. if (location.id == event.selectedId) {
  37. location.isSelected = true;
  38. }
  39. return location;
  40. }).toList();
  41. yield LocationSuccess(items: locations);
  42. } catch (_) {
  43. yield LocationFailure();
  44. }
  45. } else if (event is OnSearch) {
  46. try {
  47. final response = await repository.getLocationUnits(
  48. locationType: event.locationType, filterId: event.filterId);
  49. bool query(LocationUnit locationUnit) =>
  50. event.searchString.isEmpty ||
  51. locationUnit.name
  52. .toLowerCase()
  53. .contains(event.searchString.toLowerCase());
  54. final result = response.where(query).toList();
  55. List<LocationUnit> locations = result.map((location) {
  56. if (location.id == event.selectedId) {
  57. location.isSelected = true;
  58. }
  59. return location;
  60. }).toList();
  61. yield LocationSuccess(items: locations);
  62. } catch (_) {
  63. yield LocationFailure();
  64. }
  65. }
  66. }
  67. }