How to add multiple state in one cubit in Flutter block pattern

  Kiến thức lập trình

I’m trying to work on my academic project but I’m facing some issues. Here I create the state and the cubit I’m trying to emit 2 lists with data I get from socket in the same block but the issue is only the first fun all time emitted then I get issues in the state. How can I do that?

class GetMessageCubit extends Cubit<GetMessageState> {
  final List<MessageEntity> _messageList = [];
  final SocketService _socketService;
  final MessageUsecases _messageUsecases;
  final String userId;
  final HiveService _hiveService;

  GetMessageCubit(this._messageUsecases, this.userId, this._hiveService,
      this._socketService)
      : super(GetMessageInitial()) {
    assert(userId.isNotEmpty, "userId cannot be null or empty");

    // Set up socket event listeners
    //_socketService.onNewMessage = _handleNewMessage;
    _socketService.statusUpdate = _status;
    _socketService.onUserOnlineStatusUpdate = _handleUserOnlineStatusUpdate;
  }

  Future<void> addNewGeneralMessage(MessageEntity newMessage) async {
    try {
      print("Message received to be added/updated in general messages");

      final MsgList = List<MessageEntity>.from(state.generalMessages);

      final existingMessageIndex =
          MsgList.indexWhere((msg) => msg.sender?.id == newMessage.sender?.id);

      print("Item found at index: $existingMessageIndex");

      if (existingMessageIndex != -1) {
        MsgList.removeAt(existingMessageIndex);
      }

      MsgList.insert(0, newMessage);

      MsgList.sort((a, b) => b.timestamp!.compareTo(a.timestamp!));

      emit(GetMessageLoaded(
        generalMessages: MsgList,
      ));
      print("Messages successfully sorted and updated.");
    } catch (e) {
      emit(GetMessageError(message: e.toString()));
      print("Error adding/updating message: $e");
    }
  }

  Future<void> addNewMessages(MessageEntity newMessage) async {
    try {
      // Handle general messages
      final updatedGeneralMessages =
          List<MessageEntity>.from(state.generalMessages);
      final existingGeneralMessageIndex = updatedGeneralMessages
          .indexWhere((msg) => msg.sender?.id == newMessage.sender?.id);
      if (existingGeneralMessageIndex != -1) {
        updatedGeneralMessages.removeAt(existingGeneralMessageIndex);
      }
      updatedGeneralMessages.insert(0, newMessage);

      // Handle conversation messages
      final updatedConversationMessages =
          List<MessageEntity>.from(state.conversationMessages);
      updatedConversationMessages.insert(0, newMessage);

      // Emit new state with both updated lists
      emit(GetConversationLoaded(
        generalMessages: state.generalMessages,
        conversationMessages: updatedConversationMessages,
        onlineStatuses: state.onlineStatuses,
        status: state.status,
      ));
    } catch (e) {
      print("Error adding/updating messages: $e");
      emit(GetMessageError(message: e.toString()));
    }
  }

  socket.on('newMessage', (data) async {
    print('Received newMessage event: $data');
    final getMessageCubit = context.read<GetMessageCubit>();
    final newMessage = MessageModel.fromJson(data).toEntity();

    await getMessageCubit.addNewMessages(newMessage);

    await Future.delayed(const Duration(milliseconds: 200));

    await getMessageCubit.addNewGeneralMessage(newMessage);
  });
}

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT