Semi-implemented getting spaces feature

This commit is contained in:
Mohammad Salameh
2024-03-12 11:14:31 +03:00
parent 661d535960
commit 0f3cc453ce
25 changed files with 311 additions and 294 deletions
+22 -198
View File
@@ -1,210 +1,23 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/model/space_model.dart';
import 'package:syncrow_app/features/devices/model/ac_model.dart';
import 'package:syncrow_app/features/devices/model/curtain_model.dart';
import 'package:syncrow_app/features/devices/model/device_category_model.dart';
import 'package:syncrow_app/features/devices/model/light_model.dart';
import 'package:syncrow_app/features/devices/model/room_model.dart';
import 'package:syncrow_app/features/devices/view/widgets/ACs/acs_view.dart';
import 'package:syncrow_app/features/devices/view/widgets/curtains/curtain_view.dart';
import 'package:syncrow_app/features/devices/view/widgets/gateway/gateway_view.dart';
import 'package:syncrow_app/features/devices/view/widgets/lights/lights_view.dart';
import 'package:syncrow_app/features/devices/view/widgets/smart_door/door_view.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
import 'package:syncrow_app/services/api/network_exception.dart';
import 'package:syncrow_app/services/api/spaces_api.dart';
part 'spaces_state.dart';
class SpacesCubit extends Cubit<SpacesState> {
SpacesCubit() : super(SpacesInitial());
SpacesCubit() : super(SpacesInitial()) {
fetchSpaces();
}
static SpacesCubit get(context) => BlocProvider.of(context);
static List<SpaceModel> spaces = [
SpaceModel(
id: '0',
name: 'Home',
rooms: [
RoomModel(id: '0', name: 'Living Room', categories: [
DevicesCategoryModel(
devices: [
ACModel(
name: "Living Room AC",
id: '0',
status: false,
temperature: 20,
fanSpeed: 0,
tempMode: 0,
coolTo: 20,
type: DeviceType.AC,
image: '',
timer: null,
bounds: Bounds(
min: 20,
max: 30,
),
),
],
icon: Assets.iconsAC,
name: 'ACs',
type: DeviceType.AC,
page: const ACsView(),
),
DevicesCategoryModel(
devices: [
LightModel(
name: "Living Room Light",
id: '0',
status: false,
color: 0,
brightness: 20,
lightingMode: 1,
timer: null,
type: DeviceType.Lights,
image: '',
recentColors: [
0xFF83D9FF,
0xFFFC3E81,
0xFFC0FF66,
0xFFFDC242,
],
),
],
icon: Assets.iconsLight,
name: 'Lights',
type: DeviceType.Lights,
page: const LightsView(),
),
DevicesCategoryModel(
devices: [],
icon: Assets.iconsDoorLock,
name: 'Doors',
type: DeviceType.Door,
page: const DoorView(),
),
DevicesCategoryModel(
devices: [
CurtainModel(
openPercentage: 10,
id: "1",
name: "Living Room Curtain",
status: false,
type: DeviceType.Curtain,
image: '',
timer: null,
),
],
icon: Assets.iconsCurtain,
name: 'Curtains',
type: DeviceType.Curtain,
page: const CurtainView(),
),
DevicesCategoryModel(
devices: [],
icon: Assets.iconsGateway,
name: 'Gateway',
type: DeviceType.Gateway,
page: const GateWayView(),
),
]),
RoomModel(id: '1', name: 'Bedroom', categories: [
DevicesCategoryModel(
devices: [
ACModel(
name: "Living Room AC",
id: '0',
status: false,
temperature: 20,
fanSpeed: 0,
tempMode: 0,
coolTo: 20,
type: DeviceType.AC,
image: '',
timer: null,
bounds: Bounds(
min: 20,
max: 30,
),
),
],
icon: Assets.iconsAC,
name: 'ACs',
type: DeviceType.AC,
page: const ACsView(),
),
DevicesCategoryModel(
devices: [
LightModel(
name: "Living Room Light",
id: '0',
status: false,
color: 0,
brightness: 20,
lightingMode: 1,
timer: null,
type: DeviceType.Lights,
image: '',
recentColors: [
0xFF83D9FF,
0xFFFC3E81,
0xFFC0FF66,
0xFFFDC242,
],
),
],
icon: Assets.iconsLight,
name: 'Lights',
type: DeviceType.Lights,
page: const LightsView(),
),
DevicesCategoryModel(
devices: [],
icon: Assets.iconsDoorLock,
name: 'Doors',
type: DeviceType.Door,
page: const DoorView(),
),
DevicesCategoryModel(
devices: [
CurtainModel(
openPercentage: 10,
id: "1",
name: "Living Room Curtain",
status: false,
type: DeviceType.Curtain,
image: '',
timer: null,
),
],
icon: Assets.iconsCurtain,
name: 'Curtains',
type: DeviceType.Curtain,
page: const CurtainView(),
),
DevicesCategoryModel(
devices: [],
icon: Assets.iconsGateway,
name: 'Gateway',
type: DeviceType.Gateway,
page: const GateWayView(),
),
]),
],
),
SpaceModel(
id: '1',
name: 'Office',
rooms: [],
),
SpaceModel(
id: '2',
name: 'Parent\'s House',
rooms: [],
),
];
static List<SpaceModel> spaces = [];
SpaceModel selectedSpace = spaces.first;
SpaceModel? selectedSpace = spaces.isNotEmpty ? spaces.first : null;
RoomModel? selectedRoom;
@@ -229,7 +42,7 @@ class SpacesCubit extends Cubit<SpacesState> {
if (index == 0) {
unselectRoom();
} else {
selectedRoom = selectedSpace.rooms[index - 1];
selectedRoom = selectedSpace!.rooms![index - 1];
}
emit(RoomSelected(selectedRoom!));
}
@@ -244,7 +57,7 @@ class SpacesCubit extends Cubit<SpacesState> {
if (index == 0) {
unselectRoom();
} else {
selectedRoom = selectedSpace.rooms[index - 1];
selectedRoom = selectedSpace!.rooms![index - 1];
}
emit(RoomSelected(selectedRoom!));
}
@@ -266,5 +79,16 @@ class SpacesCubit extends Cubit<SpacesState> {
emit(RoomUnSelected());
}
//TODO implement the methods to fetch the spaces from the API
fetchSpaces() async {
emit(SpacesLoading());
try {
spaces = await SpacesAPI.getSpaces();
emit(SpacesLoaded(spaces));
} on DioException catch (e) {
emit(SpacesError(e.message ?? "Something went wrong"));
throw ServerFailure.fromDioError(e);
} catch (e) {
emit(SpacesError(e.toString()));
}
}
}
@@ -12,6 +12,12 @@ class SpacesLoaded extends SpacesState {
SpacesLoaded(this.spaces);
}
class SpacesError extends SpacesState {
final String errMessage;
SpacesError(this.errMessage);
}
class SpacesSelected extends SpacesState {
final SpaceModel space;
@@ -1,9 +1,9 @@
import 'package:syncrow_app/features/devices/model/room_model.dart';
class SpaceModel {
final String id;
final String name;
final List<RoomModel> rooms;
final int? id;
final String? name;
final List<RoomModel>? rooms;
SpaceModel({
required this.id,
@@ -21,9 +21,9 @@ class SpaceModel {
factory SpaceModel.fromJson(Map<String, dynamic> json) {
return SpaceModel(
id: json['id'],
name: json['name'],
rooms: json['rooms'],
id: int.parse(json['homeId']),
name: json['homeName'],
rooms: [],
);
}
}
+13 -7
View File
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/nav_cubit.dart';
import 'package:syncrow_app/features/app_layout/bloc/spaces_cubit.dart';
import 'package:syncrow_app/features/app_layout/view/widgets/app_body.dart';
import 'package:syncrow_app/features/app_layout/view/widgets/default_app_bar.dart';
import 'package:syncrow_app/features/app_layout/view/widgets/default_nav_bar.dart';
@@ -20,13 +21,18 @@ class AppLayout extends StatelessWidget {
statusBarIconBrightness: Brightness.light,
),
child: SafeArea(
child: Scaffold(
backgroundColor: ColorsManager.backgroundColor,
extendBodyBehindAppBar: true,
extendBody: true,
appBar: DefaultAppBar(context),
body: const AppBody(),
bottomNavigationBar: const DefaultNavBar(),
child: BlocBuilder<SpacesCubit, SpacesState>(
builder: (context, state) {
return Scaffold(
backgroundColor: ColorsManager.backgroundColor,
extendBodyBehindAppBar: true,
extendBody: true,
appBar: state is SpacesLoaded ? DefaultAppBar(context) : null,
body: const AppBody(),
bottomNavigationBar:
state is SpacesLoaded ? const DefaultNavBar() : null,
);
},
),
),
);
@@ -50,7 +50,7 @@ class AppBarHomeDropdown extends StatelessWidget {
const SizedBox(width: 5),
Expanded(
child: BodyMedium(
text: space.name,
text: space.name ?? "",
style: context.bodyMedium.copyWith(
fontSize: 15,
color: ColorsManager.textPrimaryColor,
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/nav_cubit.dart';
import 'package:syncrow_app/features/app_layout/bloc/spaces_cubit.dart';
import '../../../../generated/assets.dart';
@@ -25,10 +26,25 @@ class AppBody extends StatelessWidget {
opacity: 0.4,
),
),
child: PageView(
physics: const NeverScrollableScrollPhysics(),
controller: NavCubit.of(context).pageController,
children: NavCubit.of(context).pages,
child: BlocConsumer<SpacesCubit, SpacesState>(
listener: (context, state) {
if (state is SpacesError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.errMessage),
),
);
}
},
builder: (context, state) {
return state is! SpacesLoading
? PageView(
physics: const NeverScrollableScrollPhysics(),
controller: NavCubit.of(context).pageController,
children: NavCubit.of(context).pages,
)
: const Center(child: CircularProgressIndicator());
},
)
// NavCubit.of(context).currentPage,
);
+5 -5
View File
@@ -8,7 +8,6 @@ import 'package:syncrow_app/features/auth/model/token.dart';
import 'package:syncrow_app/features/auth/model/user_model.dart';
import 'package:syncrow_app/services/api/authentication_api.dart';
import 'package:syncrow_app/services/api/network_exception.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
part 'auth_state.dart';
@@ -35,9 +34,9 @@ class AuthCubit extends Cubit<AuthState> {
emit(AuthAgreeToTermsChanged());
}
UserModel? user;
static UserModel? user;
Token token = Token.emptyConstructor();
static Token token = Token.emptyConstructor();
// (FlutterSecureStorage().read(key :'token'));
@@ -54,7 +53,7 @@ class AuthCubit extends Cubit<AuthState> {
if (token.accessTokenIsNotEmpty) {
FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.write(
key: Constants.tokenAccessKey, value: token.accessToken);
key: Token.loginAccessTokenKey, value: token.accessToken);
user = UserModel.fromToken(token);
emit(AuthSuccess());
@@ -62,6 +61,7 @@ class AuthCubit extends Cubit<AuthState> {
emit(AuthError('Something went wrong'));
}
} on DioException catch (e) {
emit(AuthError(e.message ?? "Something went wrong"));
throw ServerFailure.fromDioError(e);
}
}
@@ -70,7 +70,7 @@ class AuthCubit extends Cubit<AuthState> {
emit(AuthLoading());
try {
FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.delete(key: Constants.tokenAccessKey);
await storage.delete(key: Token.loginAccessTokenKey);
emit(AuthLoggedOut());
} on DioException catch (e) {
throw ServerFailure.fromDioError(e);
+13 -5
View File
@@ -4,8 +4,8 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:syncrow_app/utils/helpers/decode_base64.dart';
class Token {
static const String loginAccessToken = 'access_token';
static const String loginRefreshToken = 'refreshToken';
static const String loginAccessTokenKey = 'access_token';
static const String loginRefreshTokenKey = 'refreshToken';
final String accessToken;
final String refreshToken;
@@ -16,6 +16,10 @@ class Token {
bool get accessTokenIsNotEmpty => accessToken.isNotEmpty;
bool get refreshTokenIsNotEmpty => refreshToken.isNotEmpty;
bool get isNotEmpty => accessToken.isNotEmpty && refreshToken.isNotEmpty;
Token(
this.accessToken,
this.refreshToken,
@@ -26,13 +30,17 @@ class Token {
factory Token.fromJson(Map<String, dynamic> json) {
//save token to secure storage
var storage = const FlutterSecureStorage();
storage.write(key: loginAccessToken, value: json[loginAccessToken] ?? '');
storage.write(
key: loginAccessTokenKey, value: json[loginAccessTokenKey] ?? '');
//create token object ?
return Token(json[loginAccessToken] ?? '', json[loginRefreshToken] ?? '');
return Token(
json[loginAccessTokenKey] ?? '', json[loginRefreshTokenKey] ?? '');
}
Map<String, String> toJson() => {loginRefreshToken: refreshToken};
Map<String, String> toJson() => {loginRefreshTokenKey: refreshToken};
Map<String, String> accessTokenToJson() => {loginAccessTokenKey: accessToken};
Map<String, dynamic> decodeToken() {
final parts = accessToken.split('.');
+11 -15
View File
@@ -1,7 +1,7 @@
import 'package:syncrow_app/features/auth/model/token.dart';
class UserModel {
final String? id;
final String? uuid;
final String? email;
final String? name;
final String? photoUrl;
@@ -12,18 +12,8 @@ class UserModel {
final bool? isAgreementAccepted;
//token decoded with jwt
//{
// "email": "[email protected]",
// "userId": 2,
// "uuid": "e145438c-4c62-4535-a0f4-f77958f9f9f4",
// "sessionId": "0409a7a1-6ef5-42c5-b3a1-1f15c639b301",
// "iat": 1709711675,
// "exp": 1709711975
// }
UserModel({
required this.id,
required this.uuid,
required this.email,
required this.name,
required this.photoUrl,
@@ -34,7 +24,7 @@ class UserModel {
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
id: json['id'],
uuid: json['id'],
email: json['email'],
name: json['name'],
photoUrl: json['photoUrl'],
@@ -44,12 +34,18 @@ class UserModel {
);
}
//uuid to json
Map<String, dynamic> uuIdAsJson() => {
'userUuid': uuid,
};
//from token
factory UserModel.fromToken(Token token) {
Map<String, dynamic> tempJson = token.decodeToken();
return UserModel(
id: tempJson['uuid'].toString(),
uuid: tempJson['uuid'].toString(),
email: tempJson['email'],
name: null,
photoUrl: null,
@@ -61,7 +57,7 @@ class UserModel {
Map<String, dynamic> toJson() {
return {
'id': id,
'id': uuid,
'email': email,
'name': name,
'photoUrl': photoUrl,
@@ -46,7 +46,10 @@ class DevicesViewBody extends StatelessWidget {
},
children: [
const WizardPage(),
...SpacesCubit.get(context).selectedSpace.rooms.map(
...SpacesCubit.get(context)
.selectedSpace!
.rooms!
.map(
(room) {
return RoomPage(
room: room,
@@ -40,15 +40,15 @@ class RoomsSlider extends StatelessWidget {
),
),
),
...SpacesCubit.get(context).selectedSpace.rooms.map(
...SpacesCubit.get(context).selectedSpace!.rooms!.map(
(room) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: InkWell(
onTap: () {
SpacesCubit.get(context).roomSliderPageChanged(
SpacesCubit.get(context)
.selectedSpace
.rooms
.selectedSpace!
.rooms!
.indexOf(room));
},
child: TitleMedium(
+2 -2
View File
@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_app/features/auth/model/token.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/navigation/routing_constants.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
class SplashView extends StatelessWidget {
const SplashView({super.key});
@@ -13,7 +13,7 @@ class SplashView extends StatelessWidget {
//TODO remove this delay
Future.value().then((value) async {
var isLoggedIn = await const FlutterSecureStorage()
.read(key: Constants.tokenAccessKey) !=
.read(key: Token.loginAccessTokenKey) !=
null;
if (isLoggedIn) {
Navigator.pushReplacementNamed(context, Routes.homeRoute);
-7
View File
@@ -2,11 +2,9 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:syncrow_app/services/locator.dart';
import 'package:syncrow_app/utils/bloc_observer.dart';
import 'package:syncrow_app/utils/helpers/localization_helpers.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
import 'my_app.dart';
@@ -35,11 +33,6 @@ void main() {
initialSetup();
//final SharedPreferences prefs = await SharedPreferences.getInstance();
// var isLoggedIn = (prefs.getBool('isLoggedIn') == null) ? false : prefs.getBool('isLoggedIn');
//
var storage = const FlutterSecureStorage();
bool isLoggedIn =
await (storage.read(key: Constants.tokenAccessKey)) != null;
//to save the locale in the shared preferences
await LocalizationService.saveLocale(const Locale("en", "AE"));
+5 -1
View File
@@ -1,6 +1,7 @@
abstract class ApiEndpoints {
static const String baseUrl = 'http://100.107.182.63:4001';
static const String baseUrl = 'https://syncrow.azurewebsites.net';
// Authentication
static const String signUp = '$baseUrl/authentication/user/signup';
static const String login = '$baseUrl/authentication/user/login';
static const String deleteUser = '$baseUrl/authentication/user/delete/{id}';
@@ -8,4 +9,7 @@ abstract class ApiEndpoints {
static const String verifyOtp = '$baseUrl/authentication/user/verify-otp';
static const String forgetPassword =
'$baseUrl/authentication/user/forget-password';
// Spaces
static const String spaces = '$baseUrl/home';
}
+1 -4
View File
@@ -24,10 +24,7 @@ class AuthenticationAPI {
path: ApiEndpoints.login,
body: model.toJson(),
showServerMessage: false,
expectedResponseModel: (json) {
Token token = Token.fromJson(json['data']);
return token;
});
expectedResponseModel: (json) => Token.fromJson(json['data']));
debugPrint("response: $response");
return response;
}
+35 -32
View File
@@ -1,4 +1,5 @@
import 'package:dio/dio.dart';
import 'package:syncrow_app/features/auth/bloc/auth_cubit.dart';
class HTTPInterceptor extends InterceptorsWrapper {
// @override
@@ -7,36 +8,38 @@ class HTTPInterceptor extends InterceptorsWrapper {
// return handler.next(response);
// }
//
// @override
// void onRequest(RequestOptions options,
// RequestInterceptorHandler handler) async {
// // TODO: Implement logic for adding headers to requests.
// // This method is called before a request is sent.
// super.onRequest(options, handler);
// }
//
// @override
// void onError(DioException err, ErrorInterceptorHandler handler) async {
// // TODO: Implement error handling logic.
// // This method is called when an error occurs during a request.
// super.onError(err, handler);
// }
//
// /// Validates the response and returns true if it is successful (status code 2xx).
// Future<bool> validateResponse(Response response) async {
// if (response.statusCode != null) {
// if (response.statusCode! >= 200 && response.statusCode! < 300) {
// // If the response status code is within the successful range (2xx),
// // return true indicating a successful response.
// return true;
// } else {
// // If the response status code is not within the successful range (2xx),
// // return false indicating an unsuccessful response.
// return false;
// }
// } else {
// // If the response status code is null, return false indicating an unsuccessful response.
// return false;
// }
// }
@override
void onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
//pass the token from the flutter secure storage to the request header
options.headers['Authorization'] = 'Bearer ${AuthCubit.token.accessToken}';
super.onRequest(options, handler);
}
//
// @override
// void onError(DioException err, ErrorInterceptorHandler handler) async {
// // TODO: Implement error handling logic.
// // This method is called when an error occurs during a request.
// super.onError(err, handler);
// }
//
// /// Validates the response and returns true if it is successful (status code 2xx).
// Future<bool> validateResponse(Response response) async {
// if (response.statusCode != null) {
// if (response.statusCode! >= 200 && response.statusCode! < 300) {
// // If the response status code is within the successful range (2xx),
// // return true indicating a successful response.
// return true;
// } else {
// // If the response status code is not within the successful range (2xx),
// // return false indicating an unsuccessful response.
// return false;
// }
// } else {
// // If the response status code is null, return false indicating an unsuccessful response.
// return false;
// }
// }
}
+5 -2
View File
@@ -17,8 +17,8 @@ class HTTPService {
baseUrl: ApiEndpoints.baseUrl,
receiveDataWhenStatusError: true,
followRedirects: false,
connectTimeout: const Duration(seconds: 60),
receiveTimeout: const Duration(seconds: 60),
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 5),
),
);
@@ -37,6 +37,9 @@ 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");
+3
View File
@@ -38,6 +38,9 @@ class ServerFailure extends Failure {
case DioExceptionType.unknown:
return ServerFailure("Unexpected Error, Please try again!");
default:
return ServerFailure("Unexpected Error, Please try again!");
}
}
+35
View File
@@ -0,0 +1,35 @@
import 'package:syncrow_app/features/app_layout/model/space_model.dart';
import 'package:syncrow_app/features/auth/bloc/auth_cubit.dart';
import 'package:syncrow_app/services/api/api_links_endpoints.dart';
import 'package:syncrow_app/services/api/http_service.dart';
class SpacesAPI {
// static Future<Token> loginWithEmail(
// {required LoginWithEmailModel model}) async {
// final response = await HTTPService().post(
// path: ApiEndpoints.login,
// body: model.toJson(),
// showServerMessage: false,
// expectedResponseModel: (json) {
// Token token = Token.fromJson(json['data']);
// return token;
// });
// debugPrint("response: $response");
// return response;
// }
static Future<List<SpaceModel>> getSpaces() async {
final response = await HTTPService().get(
path: "${ApiEndpoints.spaces}/${AuthCubit.user!.uuid}",
showServerMessage: false,
expectedResponseModel: (json) {
List<SpaceModel> spaces = [];
for (var space in json) {
spaces.add(SpaceModel.fromJson(space));
}
return spaces;
},
);
return response;
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ abstract class Constants {
static const double defaultPadding = 16;
static const String tokenAccessKey = 'access_token';
static const String token = '';
}
enum DeviceType {