forked from eatvio/eatvio_app
feat(chat): add chat lazy loading, send message and websocket init for notifications and new chat messages
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dart_pusher_channels/dart_pusher_channels.dart';
|
||||
import 'package:easy_debounce/easy_debounce.dart';
|
||||
@@ -8,43 +9,47 @@ import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/features/chat/models/chat_message_model.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart';
|
||||
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||
import 'package:eatvio_app/locator_service.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
final ChatRepository chatRepository;
|
||||
final InitializationCubit initializationCubit;
|
||||
|
||||
int currentPage = 1;
|
||||
late final int lastPage;
|
||||
bool isLoading = false;
|
||||
|
||||
late final PusherChannelsClient client;
|
||||
late final PrivateChannel privateChannel;
|
||||
late final PrivateChannel privateChatChannel;
|
||||
|
||||
ChatRoomCubit({
|
||||
required this.chatRepository,
|
||||
required this.initializationCubit,
|
||||
}) : super(ChatRoomState.loading());
|
||||
|
||||
loadNextPage(String chatId) async {
|
||||
if (currentPage < lastPage) {
|
||||
if (currentPage < lastPage && !isLoading) {
|
||||
isLoading = true;
|
||||
|
||||
emit(ChatRoomState.loaded(
|
||||
chatRoom: (state as ChatRoomStateLoaded).chatRoom,
|
||||
chatMessages: (state as ChatRoomStateLoaded).chatMessages,
|
||||
isTyping: (state as ChatRoomStateLoaded).isTyping,
|
||||
isLoading: true,
|
||||
isLoading: isLoading,
|
||||
));
|
||||
|
||||
try {
|
||||
final chatMessages = await chatRepository.getChatMessages(chatId, currentPage + 1);
|
||||
|
||||
isLoading = false;
|
||||
emit(ChatRoomState.loaded(
|
||||
chatRoom: (state as ChatRoomStateLoaded).chatRoom,
|
||||
chatMessages: [...(state as ChatRoomStateLoaded).chatMessages, ...chatMessages.messagesList],
|
||||
isTyping: (state as ChatRoomStateLoaded).isTyping,
|
||||
isLoading: false,
|
||||
isLoading: isLoading,
|
||||
));
|
||||
|
||||
currentPage++;
|
||||
|
||||
} catch (e) {
|
||||
print(e);
|
||||
emit(ChatRoomState.error(errorMessage: 'Ошибка получеия данных'));
|
||||
@@ -59,20 +64,13 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
final chatMessages = await chatRepository.getChatMessages(chatId, currentPage);
|
||||
lastPage = chatMessages.meta.lastPage;
|
||||
|
||||
final initCubit = sl<InitializationCubit>();
|
||||
|
||||
if (initCubit.state is InitializationStateSuccess) {
|
||||
await subscribeToChatChannel(initCubit: initCubit, chatId: chatId);
|
||||
} else {
|
||||
await initCubit.runInitialization();
|
||||
await subscribeToChatChannel(initCubit: initCubit, chatId: chatId);
|
||||
}
|
||||
await subscribeToChatChannel(initCubit: initializationCubit, chatId: chatId);
|
||||
|
||||
emit(ChatRoomState.loaded(
|
||||
chatRoom: chatRoom,
|
||||
chatMessages: chatMessages.messagesList,
|
||||
isTyping: false,
|
||||
isLoading: false,
|
||||
isLoading: isLoading,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(ChatRoomState.error(errorMessage: 'Ошибка получеия данных'));
|
||||
@@ -85,7 +83,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
}) async {
|
||||
client = (initCubit.state as InitializationStateSuccess).client;
|
||||
|
||||
privateChannel = await client.privateChannel(
|
||||
privateChatChannel = await client.privateChannel(
|
||||
'private-direct-chat.$chatId',
|
||||
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
|
||||
authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'),
|
||||
@@ -95,9 +93,9 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
),
|
||||
);
|
||||
|
||||
privateChannel.subscribe();
|
||||
privateChatChannel.subscribe();
|
||||
|
||||
privateChannel.bind('App\\Events\\ChatMessageUpdated').listen((event) {
|
||||
privateChatChannel.bind('App\\Events\\ChatMessageUpdated').listen((event) {
|
||||
List<ChatMessageModel> messagesList = [
|
||||
ChatMessageModel.fromJson(jsonDecode(event.data)['message']),
|
||||
...(state as ChatRoomStateLoaded).chatMessages,
|
||||
@@ -107,18 +105,18 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
chatRoom: (state as ChatRoomStateLoaded).chatRoom,
|
||||
chatMessages: messagesList,
|
||||
isTyping: (state as ChatRoomStateLoaded).isTyping,
|
||||
isLoading: false,
|
||||
isLoading: isLoading,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
privateChannel.bind('client-typing').listen((event) {
|
||||
privateChatChannel.bind('client-typing').listen((event) {
|
||||
emit(
|
||||
ChatRoomState.loaded(
|
||||
chatRoom: (state as ChatRoomStateLoaded).chatRoom,
|
||||
chatMessages: (state as ChatRoomStateLoaded).chatMessages,
|
||||
isTyping: true,
|
||||
isLoading: false,
|
||||
isLoading: isLoading,
|
||||
),
|
||||
);
|
||||
EasyDebounce.debounce(
|
||||
@@ -129,16 +127,24 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
chatRoom: (state as ChatRoomStateLoaded).chatRoom,
|
||||
chatMessages: (state as ChatRoomStateLoaded).chatMessages,
|
||||
isTyping: false,
|
||||
isLoading: false,
|
||||
isLoading: isLoading,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
sendMessage({
|
||||
required String chatId,
|
||||
required String data,
|
||||
required List<File> filesList,
|
||||
}) async {
|
||||
await chatRepository.sendMessage(chatId: chatId, data: data);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() async {
|
||||
privateChannel.unsubscribe();
|
||||
privateChatChannel.unsubscribe();
|
||||
super.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart';
|
||||
@@ -7,6 +5,7 @@ import 'package:eatvio_app/locator_service.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:eatvio_app/core/app_export.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:lazy_load_scrollview/lazy_load_scrollview.dart';
|
||||
|
||||
class ChatScreen extends StatefulWidget {
|
||||
final String chatId;
|
||||
@@ -22,14 +21,13 @@ class ChatScreen extends StatefulWidget {
|
||||
|
||||
class _ChatScreenState extends State<ChatScreen> {
|
||||
final scrollController = ScrollController();
|
||||
bool isLoading = false;
|
||||
final TextEditingController textEditingController = TextEditingController();
|
||||
|
||||
Widget build(BuildContext context) {
|
||||
return BlocProvider<ChatRoomCubit>(
|
||||
create: (BuildContext context) => sl()..initChat(widget.chatId),
|
||||
child: BlocBuilder<ChatRoomCubit, ChatRoomState>(
|
||||
builder: (context, state) {
|
||||
setupScrollController(context);
|
||||
if (state is ChatRoomStateLoaded) {
|
||||
return _buildChat(context, state);
|
||||
} else if (state is ChatRoomStateError) {
|
||||
@@ -51,17 +49,6 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
void setupScrollController(BuildContext context) {
|
||||
scrollController.addListener(() {
|
||||
/// todo change rule for request new page
|
||||
if (scrollController.position.atEdge) {
|
||||
if (scrollController.position.pixels != 0) {
|
||||
context.read<ChatRoomCubit>().loadNextPage(widget.chatId);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_buildChat(BuildContext context, ChatRoomStateLoaded state) {
|
||||
return Scaffold(
|
||||
resizeToAvoidBottomInset: true,
|
||||
@@ -125,37 +112,39 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
child: Container(
|
||||
color: Color(0xFFF0F2F5),
|
||||
width: double.maxFinite,
|
||||
child: CustomScrollView(
|
||||
physics: BouncingScrollPhysics(),
|
||||
controller: scrollController,
|
||||
reverse: true,
|
||||
slivers: [
|
||||
SliverPadding(
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(context, index) {
|
||||
if (index < state.chatMessages.length) {
|
||||
return ChatBubbleWidget(
|
||||
text: state.chatMessages[index].data.trim(),
|
||||
isCurrentUser: state.chatRoom.users['to_chat_user']!.id != state.chatMessages[index].authorId,
|
||||
mediaData: state.chatMessages[index].mediaData ?? [],
|
||||
);
|
||||
} else {
|
||||
Timer(const Duration(milliseconds: 30), () {
|
||||
scrollController.jumpTo(scrollController.position.maxScrollExtent);
|
||||
});
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Center(child: CupertinoActivityIndicator()),
|
||||
);
|
||||
}
|
||||
},
|
||||
childCount: state.chatMessages.length + (state.isLoading ? 1 : 0),
|
||||
child: LazyLoadScrollView(
|
||||
onEndOfPage: () => context.read<ChatRoomCubit>().loadNextPage(widget.chatId),
|
||||
isLoading: state.isLoading,
|
||||
scrollOffset: MediaQuery.of(context).size.height.toInt(),
|
||||
child: CustomScrollView(
|
||||
physics: BouncingScrollPhysics(),
|
||||
controller: scrollController,
|
||||
reverse: true,
|
||||
slivers: [
|
||||
SliverPadding(
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(context, index) {
|
||||
if (index < state.chatMessages.length) {
|
||||
return ChatBubbleWidget(
|
||||
text: state.chatMessages[index].data.trim(),
|
||||
isCurrentUser: state.chatRoom.users['to_chat_user']!.id != state.chatMessages[index].authorId,
|
||||
mediaData: state.chatMessages[index].mediaData ?? [],
|
||||
);
|
||||
} else {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Center(child: CupertinoActivityIndicator()),
|
||||
);
|
||||
}
|
||||
},
|
||||
childCount: state.chatMessages.length + (state.isLoading ? 1 : 0),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -182,6 +171,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
SizedBox(
|
||||
width: mediaQueryData.size.width - 96,
|
||||
child: TextFormField(
|
||||
controller: textEditingController,
|
||||
maxLines: 5,
|
||||
minLines: 1,
|
||||
keyboardType: TextInputType.multiline,
|
||||
@@ -228,7 +218,18 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
SizedBox(width: 8),
|
||||
InkWell(
|
||||
borderRadius: BorderRadiusStyle.circleBorder17,
|
||||
onTap: () {},
|
||||
onTap: () {
|
||||
if (textEditingController.text.isNotEmpty) {
|
||||
context.read<ChatRoomCubit>().sendMessage(
|
||||
chatId: widget.chatId,
|
||||
data: textEditingController.text.trim(),
|
||||
filesList: [],
|
||||
);
|
||||
setState(() {
|
||||
textEditingController.clear();
|
||||
});
|
||||
}
|
||||
},
|
||||
child: Ink(
|
||||
height: 32,
|
||||
width: 32,
|
||||
|
||||
@@ -13,6 +13,7 @@ import '/core/app_export.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
part 'chat_select_event.dart';
|
||||
|
||||
part 'chat_select_state.dart';
|
||||
|
||||
/// A bloc that manages the state of a ChatSelect according to the event that is dispatched to it.
|
||||
@@ -68,15 +69,19 @@ class ChatSelectBloc extends Bloc<ChatSelectEvent, ChatSelectState> {
|
||||
if (data is Map<String, dynamic> && data.containsKey('chatRooms')) {
|
||||
if (state is ChatSelectLoadedState) {
|
||||
var currentState = state as ChatSelectLoadedState;
|
||||
emit(currentState.copyWith(
|
||||
chatSelectModelObj: currentState.chatSelectModelObj,
|
||||
chatRooms: currentState.chatRooms,
|
||||
),);
|
||||
emit(
|
||||
currentState.copyWith(
|
||||
chatSelectModelObj: currentState.chatSelectModelObj,
|
||||
chatRooms: currentState.chatRooms,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
emit(ChatSelectLoadedState(
|
||||
chatRooms: fillChatEntryList(data['chatRooms']),
|
||||
//chatRooms: [],
|
||||
),);
|
||||
emit(
|
||||
ChatSelectLoadedState(
|
||||
chatRooms: fillChatEntryList(data['chatRooms']),
|
||||
//chatRooms: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
|
||||
|
||||
Reference in New Issue
Block a user