Add functionality to fetch devices by room ID

Added a new method in DevicesCubit to fetch devices by room ID and updated
related classes and API calls to support this functionality.
This commit is contained in:
Mohammad Salameh
2024-04-02 12:12:54 +03:00
parent 1397778123
commit 5dc4f96a71
8 changed files with 75 additions and 26 deletions

View File

@ -20,17 +20,13 @@ class HomeCubit extends Cubit<HomeState> {
// Create a private static instance variable
static HomeCubit? _instance;
HomeCubit._() : super(HomeInitial()) {
if (spaces != null) {
if (selectedSpace == null) {
fetchSpaces().then((value) {
if (selectedSpace != null) {
print('selectedSpace: ${selectedSpace!.name}');
fetchRooms(selectedSpace!);
}
});
}
} else {
fetchSpaces(); // this is for the first time
if (selectedSpace == null) {
fetchSpaces().then((value) {
if (selectedSpace != null) {
print('selectedSpace: ${selectedSpace!.name}');
fetchRooms(selectedSpace!);
}
});
}
}
static HomeCubit getInstance() {
@ -128,7 +124,7 @@ class HomeCubit extends Cubit<HomeState> {
fetchRooms(SpaceModel space) async {
emit(GetSpaceRoomsLoading());
try {
space.rooms = await SpacesAPI.getRooms(space.id!);
space.rooms = await SpacesAPI.getRoomsBySpaceId(space.id!);
if (space.rooms != null) {
emit(GetSpaceRoomsLoaded(space.rooms!));
} else {

View File

@ -16,6 +16,7 @@ import 'package:syncrow_app/features/devices/view/widgets/three_gang/three_gang_
import 'package:syncrow_app/features/devices/view/widgets/smart_door/door_view.dart';
import 'package:syncrow_app/services/api/devices_api.dart';
import 'package:syncrow_app/services/api/network_exception.dart';
import 'package:syncrow_app/services/api/spaces_api.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
part 'devices_state.dart';
@ -24,6 +25,9 @@ class DevicesCubit extends Cubit<DevicesState> {
DevicesCubit() : super(DevicesInitial()) {
if (HomeCubit.getInstance().selectedSpace != null) {
fetchGroups(HomeCubit.getInstance().selectedSpace!.id!);
for (var room in HomeCubit.getInstance().selectedSpace!.rooms!) {
fetchDevicesByRoomId(room.id!);
}
}
}
bool _isClosed = false;
@ -251,6 +255,26 @@ class DevicesCubit extends Cubit<DevicesState> {
}
}
fetchDevicesByRoomId(int roomId) async {
if (_isClosed) return;
try {
emit(GetDevicesLoading());
int roomIndex = HomeCubit.getInstance()
.selectedSpace!
.rooms!
.indexWhere((element) => element.id == roomId);
HomeCubit.getInstance().selectedSpace!.rooms![roomIndex].devices =
await SpacesAPI.getDevicesByRoomId(roomId);
emit(GetDevicesSuccess());
} on DioException catch (error) {
emit(
GetDevicesError(ServerFailure.fromDioError(error).errMessage),
);
}
}
///Lights
onHorizontalDragUpdate(DeviceModel light, double dx, double screenWidth) {
double newBrightness = (dx / (screenWidth - 15) * 100);

View File

@ -14,6 +14,17 @@ class DevicesFailure extends DevicesState {}
class ChangeIndex extends DevicesState {}
// Devices
class GetDevicesLoading extends DevicesState {}
class GetDevicesSuccess extends DevicesState {}
class GetDevicesError extends DevicesState {
final String errorMsg;
GetDevicesError(this.errorMsg);
}
class DevicesCategoryChanged extends DevicesState {}
class CategorySwitchChanged extends DevicesState {}

View File

@ -1,30 +1,37 @@
import 'package:syncrow_app/features/devices/model/device_category_model.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
class RoomModel {
final int? id;
final String? name;
final List<DevicesCategoryModel>? categories;
List<DeviceModel>? devices;
RoomModel({
required this.id,
required this.name,
required this.categories,
required this.devices,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'devices': categories,
'devices': devices,
};
}
factory RoomModel.fromJson(Map<String, dynamic> json) {
List<DeviceModel> devices = [];
if (json['devices'] != null) {
for (var device in json['devices']) {
devices.add(DeviceModel.fromJson(device));
}
}
return RoomModel(
id: json['roomId'],
name: json['roomName'],
categories: json['devices'],
devices: devices,
);
}
}

View File

@ -13,10 +13,6 @@ class RoomPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<DeviceModel> devices = [];
for (var category in room.categories ?? []) {
devices.addAll(category.devices);
}
return Padding(
padding: const EdgeInsets.symmetric(horizontal: Constants.defaultPadding),
child: SingleChildScrollView(
@ -32,9 +28,9 @@ class RoomPage extends StatelessWidget {
padding: const EdgeInsets.only(top: 10),
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: devices.length,
itemCount: room.devices!.length,
itemBuilder: (_, index) {
return RoomPageSwitch(device: devices[index]);
return RoomPageSwitch(device: room.devices![index]);
},
);
},

View File

@ -16,6 +16,7 @@ abstract class ApiEndpoints {
// Devices
static const String control = '$baseUrl/device/control';
static const String devicesByRoom = '$baseUrl/device/room';
//groups
static const String groups = '$baseUrl/group';

View File

@ -37,9 +37,6 @@ class HTTPService {
path,
queryParameters: queryParameters,
);
// debugPrint("status code is ${response.statusCode}");
// debugPrint("response data is ${response.data}");
return expectedResponseModel(response.data);
} catch (error) {
debugPrint("******* Error");

View File

@ -1,6 +1,7 @@
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:syncrow_app/features/app_layout/model/space_model.dart';
import 'package:syncrow_app/features/auth/model/user_model.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/features/devices/model/room_model.dart';
import 'package:syncrow_app/services/api/api_links_endpoints.dart';
import 'package:syncrow_app/services/api/http_service.dart';
@ -23,7 +24,7 @@ class SpacesAPI {
}
//get rooms by space id
static Future<List<RoomModel>> getRooms(int spaceId) async {
static Future<List<RoomModel>> getRoomsBySpaceId(int spaceId) async {
final response = await _httpService.get(
path: ApiEndpoints.rooms,
queryParameters: {"homeId": spaceId},
@ -38,4 +39,20 @@ class SpacesAPI {
);
return response;
}
static Future<List<DeviceModel>> getDevicesByRoomId(int roomId) async {
final response = await _httpService.get(
path: ApiEndpoints.devicesByRoom,
queryParameters: {"roomId": roomId, "pageSize": 10},
showServerMessage: false,
expectedResponseModel: (json) {
List<DeviceModel> devices = [];
for (var device in json['devices']) {
devices.add(DeviceModel.fromJson(device));
}
return devices;
},
);
return response;
}
}