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.

71 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(
  21. event.currentDevices, event.updatedDeviceId);
  22. } else if (event is OnSearch) {
  23. yield* _mapOnSearchToState(event.query);
  24. }
  25. }
  26. Stream<DeviceState> _mapOnSearchToState(String query) async* {
  27. yield DisplayDevice.loading();
  28. try {
  29. List<Device> devices = new List<Device>();
  30. final response = await repository.getDevices(query);
  31. devices = response;
  32. devices.sort((a, b) => (a.id).compareTo(b.id));
  33. yield DisplayDevice.data(devices);
  34. } catch (e) {
  35. yield DisplayDevice.error(AppException.handleError(e));
  36. }
  37. }
  38. Stream<DeviceState> _mapOpenScreenToState() async* {
  39. yield DisplayDevice.loading();
  40. try {
  41. List<Device> devices = new List<Device>();
  42. final response = await repository.getDevices("");
  43. devices = response;
  44. devices.sort((a, b) => (a.id).compareTo(b.id));
  45. yield DisplayDevice.data(devices);
  46. } catch (e) {
  47. yield DisplayDevice.error(AppException.handleError(e));
  48. }
  49. }
  50. Stream<DeviceState> _mapControlDeviceToState(
  51. List<Device> currentDevices, int updatedDeviceId) async* {
  52. List<Device> devices = new List<Device>();
  53. currentDevices.forEach((device) {
  54. if (device.id == updatedDeviceId) {
  55. var updatedStatus = device.status == "1" ? "0" : "1";
  56. device.status = updatedStatus;
  57. }
  58. devices.add(Device.clone(device));
  59. });
  60. yield DisplayDevice.data(devices);
  61. }
  62. }