Refactor HomeCubit class for better instance management

Create a private static instance variable and refactor methods for better instance management in the HomeCubit class.
This commit is contained in:
Mohammad Salameh
2024-04-01 12:09:01 +03:00
parent a20dfa3709
commit d1bc973b38
10 changed files with 169 additions and 145 deletions

View File

@ -17,8 +17,10 @@ import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
part 'home_state.dart';
class HomeCubit extends Cubit<HomeState> {
HomeCubit() : super(SpacesInitial()) {
if (HomeCubit.spaces != null) {
// Create a private static instance variable
static HomeCubit? _instance;
HomeCubit._() : super(HomeInitial()) {
if (spaces != null) {
if (selectedSpace == null) {
fetchSpaces().then((value) {
if (selectedSpace != null) {
@ -31,12 +33,17 @@ class HomeCubit extends Cubit<HomeState> {
fetchSpaces(); // this is for the first time
}
}
static HomeCubit getInstance() {
// If an instance already exists, return it
_instance ??= HomeCubit._();
return _instance!;
}
static HomeCubit get(context) => BlocProvider.of(context);
static List<SpaceModel>? spaces;
List<SpaceModel>? spaces;
static SpaceModel? selectedSpace;
SpaceModel? selectedSpace;
RoomModel? selectedRoom;
@ -46,7 +53,12 @@ class HomeCubit extends Cubit<HomeState> {
var duration = const Duration(milliseconds: 300);
selectSpace(SpaceModel space) {
// selectSpace(SpaceModel space) async {
// selectedSpace = space;
// emit(SpaceSelected(space));
// }
changeSelectedSpace(SpaceModel space) {
selectedSpace = space;
emit(SpaceSelected(space));
}
@ -102,7 +114,11 @@ class HomeCubit extends Cubit<HomeState> {
emit(GetSpacesLoading());
try {
spaces = await SpacesAPI.getSpaces();
selectedSpace = spaces!.isNotEmpty ? selectSpace(spaces!.first) : null;
selectedSpace = spaces!.isNotEmpty
?
// selectSpace(spaces!.first)
selectedSpace = spaces!.first
: null;
emit(GetSpacesLoaded(spaces!));
} on DioException catch (e) {
emit(GetSpacesError(ServerFailure.fromDioError(e).errMessage));