flutterfirebasegoogle-cloud-firestorechatstream-builder

Null Check operator used on a null value.//chat is available for every user


Why in this code,** chat** is for every user i want only the user who send and who he want to send but this chat is available for every user . And when i add reciever add it create this error Null Check operator used on a null value However I have reciever id: G3BXTZzjanWd4vwg4iMBv0VvkEh1 And sender id is G3BXTZzjanWd4vwg4iMBv0VvkEh1

Suppose I have reciever id

widget.id;

Here is the code without reciever id can any one solve my issue using reciever id as widget.id

StreamBuilder(
stream:FirebaseFirestore.instance.collection("messages").orderBy("Date",descending: false).snapshots(),
                  builder: (builder,AsyncSnapshot<QuerySnapshot>snapshot){
  print(snapshot.data!.docs.length);
if(!snapshot.hasData){
  return Center(child: CircularProgressIndicator(),);
}
  return ListView.builder(
      itemCount: snapshot.data!.docs.length,
      itemBuilder: (itemBuilder, index) {
        final message = snapshot.data!.docs[index]["message"];
        final senderId = snapshot.data!.docs[index]["senderid"];
        final currentUser = FirebaseAuth.instance.currentUser;
        final isMe = senderId == currentUser!.uid;
        final alignment = isMe ? MainAxisAlignment.end : MainAxisAlignment.start;
        final messageTextStyle = isMe ? TextStyle(color: Colors.white) : TextStyle(color: Colors.black);
        final messageColor = isMe ? Colors.blue : Colors.grey.shade300;
        return Row(
          mainAxisAlignment: alignment,
          children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 10, horizontal: 8),
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
              decoration: BoxDecoration(
                color: messageColor,
                borderRadius: BorderRadius.only(
                  topLeft: isMe ? Radius.circular(20) : Radius.circular(0),
                  topRight: isMe ? Radius.circular(0) : Radius.circular(20),
                  bottomLeft: Radius.circular(20),
                  bottomRight: Radius.circular(20),
                ),
              ),
              child: Text(
                message,
                style: messageTextStyle,
              ),
            ),
          ],
        );
      });
                  }),
     IconButton(
                    onPressed: ()async {
                      print("ID=="+widget.id);
                      if (messagecontroller.text.isNotEmpty) {
                        FirebaseFirestore.instance.collection("messages").add({
                          "senderid":FirebaseAuth.instance.currentUser!.uid,
                          "recieverid":"null",
                          "Date":DateTime.now(),
                          "message":messagecontroller.text.toString(),

                        }).whenComplete(() {

                          Fluttertoast.showToast(msg: "Send message to ${widget.name}........."
                              ,
                              backgroundColor: Colors.grey,
                            timeInSecForIosWeb: 1
                          );
                        });
                        messagecontroller.clear();
                      }  
else{
  Fluttertoast.showToast(msg: "Please Enter text to send message to ${widget.name}"
  ,
  backgroundColor: Colors.red
  );
                      }

                    },
                    icon: Icon(Icons.send),
                    color: Colors.grey,
                  ),

Solution

  • You're loading the chat messages with (lines wrapped for readability):

    FirebaseFirestore.instance
      .collection("messages")
      .orderBy("Date",descending: false)
      .snapshots()
    

    So that loads all messages, regardless of the ender and/or receiver.

    If you only want to load messages for a specific sender/receiver pair, you'll want to use a query:

    FirebaseFirestore.instance
      .collection("messages")
      .orderBy("Date",descending: false)
      .where("senderid", isEqualTo: "G3BXTZzjanWd4vwg4iMBv0VvkEh1")
      .where("recieverid", isEqualTo: "G3BXTZzjanWd4vwg4iMBv0VvkEh1")
      .snapshots()
    

    You'll of course want to match the conditions and values to fit with your actual code.


    Note that you have taken a rather relational data model approach here by storing the chat messages for all users in collection (like you'd do in a single table in SQL).

    While this may work, there are many other possible data models. Consider reading up on NoSQL data modeling and watching the excellent Get to know Cloud Firestore video series to learn more about your options.