Home > Mobile >  How can I save messages on firestore and display the messages on screen?
How can I save messages on firestore and display the messages on screen?

Time:10-19

I have been working on the messaging functionality of an app that I am currently working on. I have implemented the Firestore code however, it is storing the messages in the collection and as well as not displaying the messages on-screen. The message is still left on the Text Field. Below is the code and any assistance will be highly appreciated.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class MessageCenter extends StatefulWidget {
  const MessageCenter({super.key});

  @override
  State<MessageCenter> createState() => _MessageCenterState();
}

class _MessageCenterState extends State<MessageCenter> {
  final TextEditingController _text = TextEditingController();
  final firestore = FirebaseFirestore.instance;
  final auth = FirebaseAuth.instance;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          StreamBuilder(
              stream: firestore
                  .collection('chatrooms')
                  .doc()
                  .collection('message')
                  .snapshots(),
              builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                return snapshot.hasData
                    ? Expanded(
                        child: ListView.builder(
                            reverse: true,
                            itemCount: snapshot.data!.docs.length,
                            itemBuilder: (context, i) {
                              return Card(
                                child: Text(
                                  snapshot.data!.docs[i]['msg'],
                                ),
                              );
                            }),
                      )
                    : Container();
              }),
          SizedBox(
            height: 55,
            child: Row(
              children: [
                Expanded(
                  flex: 5,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white30,
                        borderRadius: BorderRadius.circular(11),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                            controller: _text,
                            decoration: const InputDecoration(
                              hintText: 'Write Message',
                            )),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: InkWell(
                      onTap: () {
                        firestore
                            .collection('chatrooms')
                            .doc('chatrooms')
                            .collection('message')
                            .add({
                          'sender': auth.currentUser!.email,
                          'time': DateFormat('hh:mm').format(DateTime.now()),
                          'msg': _text.text,
                        });
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.deepOrange,
                          borderRadius: BorderRadius.circular(11),
                        ),
                        child: const Center(
                          child: Icon(
                            Icons.send,
                            size: 30,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

to save message to firestore, you need first of all create model class, firestoreService class, chatRoomRepository class, chatRepository class, chatService class, and controller class`. this is for proper separation of concern and organizing business logic. But for the purposes of this demo, here is the basic function for saving your message to firestore.

  
  Future<void> saveMessage() async {
    final chatRoomId = 'your_chatRoom_id_here';
    final messageId = 'your_message_id_here';
    final path = 'chatRooms/$chatRoomId/messages/$messageId';
    final _service = FirebaseFirestore.instance.doc(path);
    final sender = auth.currentUser!.email;
    final time = DateFormat('hh:mm').format(DateTime.now());
    final msg = _text.text;
try{
      await _service
        .set({
        "id": messageId,
        'sender': sender, 
        'time': time, 
        'msg': msg
        });
} on FirebaseException catch(e){
  print(e);
}
  }

  • Related