Flutter (16) Exchange Message

Huisu·2023년 3월 11일
0

Flutter

목록 보기
16/21
post-thumbnail

message

  • message.dart 파일 만들어서 message 객체 만들기

    import 'package:cloud_firestore/cloud_firestore.dart';
    
    class Message {
      String? senderId;
      String? receiverId;
      String? type;
      String? message;
      Timestamp? timestamp;
      String? photoUrl;
    
      Message(
          {this.senderId,
            this.receiverId,
            this.type,
            this.message,
            this.timestamp});
    
      //Will be only called when you wish to send an image
      // named constructor
      Message.imageMessage(
          {this.senderId,
            this.receiverId,
            this.message,
            this.type,
            this.timestamp,
            this.photoUrl});
    
      Map toMap() {
        var map = Map<String, dynamic>();
        map['senderId'] = this.senderId;
        map['receiverId'] = this.receiverId;
        map['type'] = this.type;
        map['message'] = this.message;
        map['timestamp'] = this.timestamp;
        return map;
      }
    
      Map toImageMap() {
        var map = Map<String, dynamic>();
        map['message'] = this.message;
        map['senderId'] = this.senderId;
        map['receiverId'] = this.receiverId;
        map['type'] = this.type;
        map['timestamp'] = this.timestamp;
        map['photoUrl'] = this.photoUrl;
        return map;
      }
    
      // named constructor
      Message.fromMap(Map<String, dynamic> map) {
        this.senderId = map['senderId'];
        this.receiverId = map['receiverId'];
        this.type = map['type'];
        this.message = map['message'];
        this.timestamp = map['timestamp'];
        this.photoUrl = map['photoUrl'];
      }
    }

send Massage

  • send 버튼 눌렀을 때 함수로 연결되도록 코드 작성

  • sendMessage 함수 작성

    sendMessage() {
        var text = textFieldController.text;
    
        Message _message = Message(
          receiverId: widget.receiver.uid,
          senderId: sender.uid,
          message: text,
          timestamp: FieldValue.serverTimestamp(),
          type: 'text',
        );
    
        setState(() {
          isWriting = false;
        });
    
        textFieldController.text = "";
        _repository.addMessageToDb(_message, sender, widget.receiver);
      }

addMessageToDb

  • firebase repository에 함수 선언
  • firebase methods에 함수 구현

messageList

  • messageList 함수 수정

    Widget messageList() {
        return StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection("messages")
              .doc(_currentUserId)
              .collection(widget.receiver.uid!)
              .orderBy("timestamp", descending: true)
              .snapshots(),
          builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.data == null) {
              return Center(child: CircularProgressIndicator());
            }
            return ListView.builder(
              padding: EdgeInsets.all(10),
              itemCount: snapshot.data?.docs.length,
              itemBuilder: (context, index) {
                // mention the arrow syntax if you get the time
                return chatMessageItem(snapshot.data?.docs[index]);
              },
            );
          },
        );
      }

senderLayout

  • senderLayout 함수 수정

    Widget chatMessageItem(DocumentSnapshot snapshot) {
        return Container(
          margin: EdgeInsets.symmetric(vertical: 15),
          child: Container(
            alignment: snapshot['senderId'] == _currentUserId
                ? Alignment.centerRight
                : Alignment.centerLeft,
            child: snapshot['senderid'] == _currentUserId
                ? senderLayout(snapshot)
                : receiverLayout(),
          ),
        );
      }

senderLayout

  • senderlayout 코드 수정

    Widget senderLayout(DocumentSnapshot snapshot) {
        Radius messageRadius = Radius.circular(10);
        return Container(
          margin: EdgeInsets.only(top: 12),
          constraints:
            BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.65),
          decoration: BoxDecoration(
            color: UniversalVariables.senderColor,
            borderRadius: BorderRadius.only(
              topLeft: messageRadius,
              topRight: messageRadius,
              bottomLeft: messageRadius,
            ),
          ),
          child: Padding(
            padding: EdgeInsets.all(10),
            child: getMessage(snapshot)
          ),
        );
      }

getMessage

  • getmessage 함수 작성

    getMessage(DocumentSnapshot snapshot) {
        return Text(
          snapshot['message'],
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.0,
          ),
        );
      }

구현 화면

0개의 댓글