空检查操作符用于空值。// 聊天对每个用户都可用

huangapple go评论66阅读模式
英文:

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,
),
英文:

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(&quot;messages&quot;).orderBy(&quot;Date&quot;,descending: false).snapshots(),
                  builder: (builder,AsyncSnapshot&lt;QuerySnapshot&gt;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][&quot;message&quot;];
        final senderId = snapshot.data!.docs[index][&quot;senderid&quot;];
        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(&quot;ID==&quot;+widget.id);
                      if (messagecontroller.text.isNotEmpty) {
                        FirebaseFirestore.instance.collection(&quot;messages&quot;).add({
                          &quot;senderid&quot;:FirebaseAuth.instance.currentUser!.uid,
                          &quot;recieverid&quot;:&quot;null&quot;,
                          &quot;Date&quot;:DateTime.now(),
                          &quot;message&quot;:messagecontroller.text.toString(),

                        }).whenComplete(() {

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

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

答案1

得分: 0

你正在加载聊天消息,使用以下代码(为了可读性而换行):

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

这会加载所有的消息,无论发送者和/或接收者是谁。

如果你只想加载特定发送者/接收者对的消息,你可以使用查询:

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

当然,你需要根据你的实际代码来匹配条件和值。


请注意,你采用了一种相对关系数据模型的方法,将所有用户的聊天消息存储在一个集合中(就像在SQL中的单个表中一样)。

尽管这种方法可以工作,但还有许多其他可能的数据模型。考虑阅读有关NoSQL数据建模,并观看出色的了解Cloud Firestore视频系列,以了解更多有关你的选择的信息。

英文:

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

FirebaseFirestore.instance
  .collection(&quot;messages&quot;)
  .orderBy(&quot;Date&quot;,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(&quot;messages&quot;)
  .orderBy(&quot;Date&quot;,descending: false)
  .where(&quot;senderid&quot;, isEqualTo: &quot;G3BXTZzjanWd4vwg4iMBv0VvkEh1&quot;)
  .where(&quot;recieverid&quot;, isEqualTo: &quot;G3BXTZzjanWd4vwg4iMBv0VvkEh1&quot;)
  .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.

huangapple
  • 本文由 发表于 2023年2月23日 20:00:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544539.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定