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,7 +20,6 @@ class HomeCubit extends Cubit<HomeState> {
// Create a private static instance variable // Create a private static instance variable
static HomeCubit? _instance; static HomeCubit? _instance;
HomeCubit._() : super(HomeInitial()) { HomeCubit._() : super(HomeInitial()) {
if (spaces != null) {
if (selectedSpace == null) { if (selectedSpace == null) {
fetchSpaces().then((value) { fetchSpaces().then((value) {
if (selectedSpace != null) { if (selectedSpace != null) {
@ -29,9 +28,6 @@ class HomeCubit extends Cubit<HomeState> {
} }
}); });
} }
} else {
fetchSpaces(); // this is for the first time
}
} }
static HomeCubit getInstance() { static HomeCubit getInstance() {
// If an instance already exists, return it // If an instance already exists, return it
@ -128,7 +124,7 @@ class HomeCubit extends Cubit<HomeState> {
fetchRooms(SpaceModel space) async { fetchRooms(SpaceModel space) async {
emit(GetSpaceRoomsLoading()); emit(GetSpaceRoomsLoading());
try { try {
space.rooms = await SpacesAPI.getRooms(space.id!); space.rooms = await SpacesAPI.getRoomsBySpaceId(space.id!);
if (space.rooms != null) { if (space.rooms != null) {
emit(GetSpaceRoomsLoaded(space.rooms!)); emit(GetSpaceRoomsLoaded(space.rooms!));
} else { } 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/features/devices/view/widgets/smart_door/door_view.dart';
import 'package:syncrow_app/services/api/devices_api.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/network_exception.dart';
import 'package:syncrow_app/services/api/spaces_api.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart'; import 'package:syncrow_app/utils/resource_manager/constants.dart';
part 'devices_state.dart'; part 'devices_state.dart';
@ -24,6 +25,9 @@ class DevicesCubit extends Cubit<DevicesState> {
DevicesCubit() : super(DevicesInitial()) { DevicesCubit() : super(DevicesInitial()) {
if (HomeCubit.getInstance().selectedSpace != null) { if (HomeCubit.getInstance().selectedSpace != null) {
fetchGroups(HomeCubit.getInstance().selectedSpace!.id!); fetchGroups(HomeCubit.getInstance().selectedSpace!.id!);
for (var room in HomeCubit.getInstance().selectedSpace!.rooms!) {
fetchDevicesByRoomId(room.id!);
}
} }
} }
bool _isClosed = false; 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 ///Lights
onHorizontalDragUpdate(DeviceModel light, double dx, double screenWidth) { onHorizontalDragUpdate(DeviceModel light, double dx, double screenWidth) {
double newBrightness = (dx / (screenWidth - 15) * 100); double newBrightness = (dx / (screenWidth - 15) * 100);

View File

@ -14,6 +14,17 @@ class DevicesFailure extends DevicesState {}
class ChangeIndex extends DevicesState {} class ChangeIndex extends DevicesState {}
// Devices // Devices
class GetDevicesLoading extends DevicesState {}
class GetDevicesSuccess extends DevicesState {}
class GetDevicesError extends DevicesState {
final String errorMsg;
GetDevicesError(this.errorMsg);
}
class DevicesCategoryChanged extends DevicesState {} class DevicesCategoryChanged extends DevicesState {}
class CategorySwitchChanged 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_category_model.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
class RoomModel { class RoomModel {
final int? id; final int? id;
final String? name; final String? name;
final List<DevicesCategoryModel>? categories; List<DeviceModel>? devices;
RoomModel({ RoomModel({
required this.id, required this.id,
required this.name, required this.name,
required this.categories, required this.devices,
}); });
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
'id': id, 'id': id,
'name': name, 'name': name,
'devices': categories, 'devices': devices,
}; };
} }
factory RoomModel.fromJson(Map<String, dynamic> json) { 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( return RoomModel(
id: json['roomId'], id: json['roomId'],
name: json['roomName'], name: json['roomName'],
categories: json['devices'], devices: devices,
); );
} }
} }

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; 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/app_layout/model/space_model.dart';
import 'package:syncrow_app/features/auth/model/user_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/features/devices/model/room_model.dart';
import 'package:syncrow_app/services/api/api_links_endpoints.dart'; import 'package:syncrow_app/services/api/api_links_endpoints.dart';
import 'package:syncrow_app/services/api/http_service.dart'; import 'package:syncrow_app/services/api/http_service.dart';
@ -23,7 +24,7 @@ class SpacesAPI {
} }
//get rooms by space id //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( final response = await _httpService.get(
path: ApiEndpoints.rooms, path: ApiEndpoints.rooms,
queryParameters: {"homeId": spaceId}, queryParameters: {"homeId": spaceId},
@ -38,4 +39,20 @@ class SpacesAPI {
); );
return response; 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;
}
} }