Multiple states for chatRoom select

This commit is contained in:
2024-04-25 14:13:52 +03:00
parent 6db3caf969
commit f5ac02c020
4 changed files with 120 additions and 92 deletions

View File

@@ -62,12 +62,17 @@ class ChatSelectBloc extends Bloc<ChatSelectEvent, ChatSelectState> {
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
if (data is Map<String, dynamic>) {
if (data is Map<String, dynamic> && data.containsKey('chatRooms')) {
if (state is ChatSelectLoadedState) {
var currentState = state as ChatSelectLoadedState;
emit(currentState.copyWith());
emit(currentState.copyWith(
chatSelectModelObj: currentState.chatSelectModelObj,
chatRooms: currentState.chatRooms,
));
} else {
emit(ChatSelectLoadedState());
emit(ChatSelectLoadedState(
chatRooms: data['chatRooms'],
));
}
} else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
@@ -80,7 +85,7 @@ class ChatSelectBloc extends Bloc<ChatSelectEvent, ChatSelectState> {
}
} catch (e) {
// Ошибка при декодировании JSON или другая ошибка выполнения
emit(ChatSelectErrorState('Ошибка при получении данных профиля: $e'));
emit(ChatSelectErrorState('Ошибка при получении данных о чатах: $e'));
}
}
}

View File

@@ -11,33 +11,39 @@ class ChatSelectState extends Equatable {
ChatSelectModel? chatSelectModelObj;
@override
List<Object?> get props => [
chatSelectModelObj,
];
ChatSelectState copyWith({
ChatSelectModel? chatSelectModelObj,
}) {
List<Object?> get props => [chatSelectModelObj];
ChatSelectState copyWith({ChatSelectModel? chatSelectModelObj}) {
return ChatSelectState(
chatSelectModelObj: chatSelectModelObj ?? this.chatSelectModelObj,
);
}
}
class ChatSelectInitialState extends ChatSelectState {
ChatSelectInitialState({required ChatSelectModel chatSelectModelObj})
: super(chatSelectModelObj: chatSelectModelObj);
}
class ChatSelectLoadedState extends ChatSelectState {
ChatSelectLoadedState({
this.chatRooms,
this.searchController,
this.chatSelectModelObj,
}) : super(chatSelectModelObj: null);
List<dynamic>? chatRooms;
TextEditingController? searchController;
ChatSelectModel? chatSelectModelObj;
@override
List<Object?> get props => [
chatSelectModelObj,
];
List<Object?> get props => [chatSelectModelObj, chatRooms, searchController];
ChatSelectLoadedState copyWith({
ChatSelectModel? chatSelectModelObj,
TextEditingController? searchController,
List<dynamic>? chatRooms,
}) {
return ChatSelectLoadedState(
chatSelectModelObj: chatSelectModelObj ?? this.chatSelectModelObj,
chatRooms: chatRooms ?? this.chatRooms,
searchController: searchController ?? this.searchController,
);
}
}

View File

@@ -17,87 +17,103 @@ class ChatSelectScreen extends StatelessWidget {
child: ChatSelectScreen());
}
@override
Widget build(BuildContext context) {
mediaQueryData = MediaQuery.of(context);
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
width: double.maxFinite,
decoration: AppDecoration.fillGray,
child: Column(
children: [
SizedBox(height: 30.v),
Container(
margin: EdgeInsets.only(
left: 16.h,
right: 20.h,
),
padding: EdgeInsets.all(12.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
BlocSelector<ChatSelectBloc, ChatSelectState,
TextEditingController?>(
selector: (state) => TextEditingController(),
builder: (context, searchController) {
return CustomSearchView(
controller: searchController,
hintText: "Поиск",
);
},
),
SizedBox(height: 20.v),
_buildChatList(context)
],
),
)
],
),
),
bottomNavigationBar: _buildBottomBar(context)),
);
}
_buildChatList(BuildContext context) {
return BlocSelector<ChatSelectBloc, ChatSelectState, ChatSelectModel?>(
selector: (state) => state.chatSelectModelObj,
builder: (context, chatSelectModelObj) {
return ListView.separated(
shrinkWrap: true,
separatorBuilder: (context, index) {
return SizedBox(
height: 10.v,
);
},
itemCount: chatSelectModelObj?.userprofileItemList.length ?? 0,
itemBuilder: (context, index) {
ChatItemModel model =
chatSelectModelObj?.userprofileItemList[index] ??
ChatItemModel();
return UserprofileItemWidget(
model,
);
},
);
return BlocBuilder<ChatSelectBloc, ChatSelectState>(
builder: (context, state) {
if (state is ChatSelectInitialState) {
// Это начальное состояние, данные ещё не загружены.
return Container(
color: Colors.white,
);
} else if (state is ChatSelectLoadedState) {
// Данные загружены, можно строить экран.
return _buildScreen(context, state);
} else if (state is ChatSelectErrorState) {
// Произошла ошибка при загрузке данных.
return Center(child: Text(state.errorMessage));
} else {
// Другие состояния, если они есть.
return Container(); // Пустой контейнер для необработанных состояний.
}
},
);
}
_buildBottomBar(BuildContext context) {
return CustomBottomBar(onChanged: (BottomBarEnum type) {});
_buildScreen(BuildContext context, ChatSelectLoadedState state) {
mediaQueryData = MediaQuery.of(context);
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
width: double.maxFinite,
decoration: AppDecoration.fillGray,
child: Column(
children: [
SizedBox(height: 30.v),
Container(
margin: EdgeInsets.only(
left: 16.h,
right: 20.h,
),
padding: EdgeInsets.all(12.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CustomSearchView(
controller: state.searchController,
hintText: "Поиск",
),
SizedBox(height: 20.v),
_buildChatList(context),
ElevatedButton(
onPressed: (() => print(state.chatRooms)),
child: Text("asdasd"))
],
),
)
],
),
),
bottomNavigationBar: _buildBottomBar(context)));
}
}
_buildChatList(BuildContext context) {
return BlocSelector<ChatSelectBloc, ChatSelectState, ChatSelectModel?>(
selector: (state) => state.chatSelectModelObj,
builder: (context, chatSelectModelObj) {
return ListView.separated(
shrinkWrap: true,
separatorBuilder: (context, index) {
return SizedBox(
height: 10.v,
);
},
itemCount: chatSelectModelObj?.userprofileItemList.length ?? 0,
itemBuilder: (context, index) {
ChatItemModel model =
chatSelectModelObj?.userprofileItemList[index] ?? ChatItemModel();
return UserprofileItemWidget(
model,
);
},
);
},
);
}
_buildBottomBar(BuildContext context) {
return CustomBottomBar(onChanged: (BottomBarEnum type) {});
}

View File

@@ -34,7 +34,7 @@ class MyProfileBloc extends Bloc<MyProfileEvent, MyProfileState> {
); // Если токен есть, запускаем приложение
}
//final token =
// "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a";
// "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1ne AggmpR2TidVGDPN34fa201a";
final response = await http.get(
Uri.parse(dotenv.env['SERVER_ROOT']! + '/profile/index'),
headers: {
@@ -95,6 +95,7 @@ class MyProfileBloc extends Bloc<MyProfileEvent, MyProfileState> {
selectedCity: currentState.selectedCity,
selectedCountry: currentState.selectedCountry,
selectedActivity: currentState.selectedActivity,
myProfileModelObj: currentState.myProfileModelObj,
));
} else {
var plans = []