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.

56 lines
1.6KB

  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. }
  23. }
  24. Stream<DeviceState> _mapOpenScreenToState() async* {
  25. yield DisplayDevice.loading();
  26. try {
  27. List<Device> devices = new List<Device>();
  28. final response = await repository.getDevices();
  29. devices = response;
  30. devices.sort((a, b) => (a.id).compareTo(b.id));
  31. yield DisplayDevice.data(devices);
  32. } catch (e) {
  33. yield DisplayDevice.error(AppException.handleError(e));
  34. }
  35. }
  36. Stream<DeviceState> _mapControlDeviceToState(
  37. List<Device> currentDevices, int updatedDeviceId) async* {
  38. List<Device> devices = new List<Device>();
  39. currentDevices.forEach((device) {
  40. if (device.id == updatedDeviceId) {
  41. var updatedStatus = device.status == "1" ? "0" : "1";
  42. device.status = updatedStatus;
  43. }
  44. devices.add(Device.clone(device));
  45. });
  46. yield DisplayDevice.data(devices);
  47. }
  48. }