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/custom_model/Device.dart';
  5. import 'package:farm_tpf/data/api/app_exception.dart';
  6. import 'package:farm_tpf/data/repository/repository.dart';
  7. import 'package:meta/meta.dart';
  8. part 'device_event.dart';
  9. part 'device_state.dart';
  10. class DeviceBloc extends Bloc<DeviceEvent, DeviceState> {
  11. final Repository repository;
  12. DeviceBloc({required this.repository}) : super(DeviceInitial());
  13. @override
  14. Stream<DeviceState> mapEventToState(
  15. DeviceEvent event,
  16. ) async* {
  17. if (event is OpenScreen) {
  18. yield* _mapOpenScreenToState();
  19. } else if (event is ControlDevice) {
  20. yield* _mapControlDeviceToState(event.currentDevices, event.updatedDeviceId);
  21. } else if (event is OnSearch) {
  22. yield* _mapOnSearchToState(event.query);
  23. }
  24. }
  25. Stream<DeviceState> _mapOnSearchToState(String query) async* {
  26. yield DisplayDevice.loading();
  27. try {
  28. List<Device> devices = <Device>[];
  29. final response = await repository.getDevices(query);
  30. devices = response;
  31. devices.sort((a, b) => (a.id)!.compareTo(b.id!));
  32. yield DisplayDevice.data(devices);
  33. } catch (e) {
  34. yield DisplayDevice.error(AppException.handleError(e));
  35. }
  36. }
  37. Stream<DeviceState> _mapOpenScreenToState() async* {
  38. yield DisplayDevice.loading();
  39. try {
  40. List<Device> devices = <Device>[];
  41. final response = await repository.getDevices("");
  42. devices = response;
  43. devices.sort((a, b) => (a.id)!.compareTo(b.id!));
  44. yield DisplayDevice.data(devices);
  45. } catch (e) {
  46. yield DisplayDevice.error(AppException.handleError(e));
  47. }
  48. }
  49. Stream<DeviceState> _mapControlDeviceToState(List<Device> currentDevices, int updatedDeviceId) async* {
  50. List<Device> devices = <Device>[];
  51. currentDevices.forEach((device) {
  52. if (device.id == updatedDeviceId) {
  53. var updatedStatus = device.status == "1" ? "0" : "1";
  54. device.status = updatedStatus;
  55. }
  56. devices.add(Device.clone(device));
  57. });
  58. yield DisplayDevice.data(devices);
  59. }
  60. }