[Flutter/Firebase] FireStore로 Flutter에서 채팅 구현하기(2) 채팅 모듈

찌니·2023년 3월 30일
0

지난 편에 이어서 구조를 짜자면
유저가 작성자에게 contact하면 먼저 채팅방이 생성되어있는지 확인합니다.
기존 채팅방이 존재할 시 기존의 채팅방으로 이동하며, 존재하지 않을 시 첫 메세지 전송시 새로운 채팅방을 생성합니다

채팅방의 ID는 작성자+유저ID로 구성되어있기 때문에 기존 채팅방이 존재하면 새로 생성되지 않습니다

1. 기존 채팅방이 생성되어 있는지 확인

(firestore에는 채팅룸 데이터와 개인의 채팅룸의 데이터가 있습니다)

이런 너낌스 유저마다 자신의 포함된 채팅Id 데이터를 갖고 있습니다

onButtonPressed(String chatroomId) async {
      final chatList = await ChatService().getChatList(); // 유저가 갖고 있는 모든 채팅방의 정보를 가지고 오는 메소드
      bool isExist = chatList
          .map(
            (e) => e.chatRoomId,
          )
          .toList()
          .contains(chatroomId);
      if (isExist) {
        //기존 채팅방으로 이동
      } else {
        //새로운 채팅방으로 이동
      }
    }
Future<List<String>> getChatList() async {
    try {
      final snapshot =
          await _firestore.collection('users').doc(userEmail).get();
      if (snapshot.exists) {
        final List<String> chats = [];
        (snapshot.data() as Map)
            .entries
            .map((e) => chats.add(e))
            .toList();

        return chats;
      } else {
        return [];
      }
    } catch (e) {
      throw e;
    }
  }

2. 기존 채팅방 존재시 채팅 Stream 연결

 Stream<ChatRoom> getChatRoomData(String chatroomId) {
    try {
      final stream = _firestore
          .collection('chatrooms')
          .doc(chatroomId)
          .snapshots()
          .map((event) => ChatRoom.fromDocumentSnapshot(event));

      return stream;
    } catch (e) {
      throw e;
    }
  }


stream을 사용하는 부분입니다

3. 기존 채팅방이 존재하지 않을 시 새 채팅방 생성

Future newChatRoom(ChatRoom chatroom, Message message) async {
    _firestore
        .collection('chatrooms')
        .doc(chatroom.chatRoomId)
        .set(chatroom.toJson());
  }

4. 메세지 전송

 void sendMessage(String chatRoomId, Message message) async {
    try {
      final snapshot =
          await _firestore.collection('chatrooms').doc(chatRoomId).get();
      if (snapshot.exists) {
        final roomData = ChatRoom.fromDocumentSnapshot(snapshot);
        final messages = roomData.messages;
        messages.add(message);
        _firestore
            .collection('chatrooms')
            .doc(chatRoomId)
            .update({'messages': messages.map((e) => e.toJson()).toList()});
      }

    } catch (e) {
      print(e);
    }
  }

해당 코드 깃링크
https://github.com/PoomAt-E/hobby-mate
https://github.com/2023-GSC-Diviction/Diviction-User

profile
찌니's develog

0개의 댓글