Flutter误差:“是文档()”:不是真的

vdzxcuhz  于 2023-01-21  发布在  Flutter
关注(0)|答案(1)|浏览(131)

我正在用flutter做一个聊天详细页面。但是,我在流部分得到这个错误。我对flutter没有太多经验。我两天都不能解决它。
错误:

Exception has occurred.
_AssertionError ('package:cloud_firestore_platform_interface/src/internal/pointer.dart': Failed assertion: line 56 pos 12: 'isDocument()': is not true.)

代码:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_bubble/bubble_type.dart';
import 'package:flutter_chat_bubble/chat_bubble.dart';
import 'package:flutter_chat_bubble/clippers/chat_bubble_clipper_6.dart';

class Chat extends StatefulWidget {
  Chat({super.key, required this.friendUid, required this.friendName});
  final String friendUid;
  final String friendName;

  @override
  State<Chat> createState() => _ChatState(friendUid, friendName);
}

class _ChatState extends State<Chat> {
  CollectionReference chats = FirebaseFirestore.instance.collection("chats");
  final friendUid;
  final friendName;
  final currentUserUid = FirebaseAuth.instance.currentUser!.uid;
  var chatDocId;
  var _controller = TextEditingController();

  _ChatState(this.friendName, this.friendUid);

  @override
  void initState() {
    chats
        .where("users", isEqualTo: {friendUid: null, currentUserUid: null})
        .limit(1)
        .get()
        .then(
          (QuerySnapshot snapshotx) {
            if (snapshotx.docs.isNotEmpty) {
              chatDocId = snapshotx.docs.single.id;
            } else {
              chats.add({
                "users": {currentUserUid: null, friendUid: null},
              }).then((value) {
                chatDocId = value;
              });
            }
          },
        )
        .catchError(() {});
    super.initState();
  }

  void sendMessage(String msg) {
    if (msg == "") return;
    chats.doc(chatDocId.toString()).collection("messages").add({
      "createdOn": FieldValue.serverTimestamp(),
      "uid": currentUserUid,
      "msg": msg
    }).then((value) {
      _controller.text = "";
    });
  }

  bool isSender(String friend) {
    return friend == currentUserUid;
  }

  Alignment getAlignment(String friend) {
    if (friend == currentUserUid) {
      return Alignment.topRight;
    }
    return Alignment.topLeft;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("chat")),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: [
              Expanded(
                  child: StreamBuilder<QuerySnapshot>(
                      stream: chats
                          .doc(chatDocId.toString())
                          .collection("messages") ==> the error part
                          .orderBy("createdOn", descending: true)
                          .snapshots(),
                      builder: (BuildContext context,
                          AsyncSnapshot<QuerySnapshot> snapshot) {
                        if (snapshot.hasError) {
                          return const Center(
                            child: Text("Error"),
                          );
                        }
                        if (snapshot.connectionState ==
                            ConnectionState.waiting) {
                          return Center(child: CircularProgressIndicator());
                        }
                        if (snapshot.hasData) {
                          return ListView(
                              reverse: true,
                              children: snapshot.data!.docs
                                  .map((DocumentSnapshot documentSnapshot) {
                                Map<String, dynamic> data = documentSnapshot
                                    .data() as Map<String, dynamic>;

                                return ChatBubble(
                                  clipper: ChatBubbleClipper6(
                                      nipSize: 0,
                                      radius: 0,
                                      type: isSender(data["uid"].toString())
                                          ? BubbleType.sendBubble
                                          : BubbleType.receiverBubble),
                                  alignment:
                                      getAlignment(data["uid"].toString()),
                                  margin: EdgeInsets.only(top: 20),
                                  backGroundColor:
                                      isSender(data["uid"].toString())
                                          ? Color(0xFF08C187)
                                          : Color(0xffE7E7ED),
                                  child: Container(
                                      constraints: BoxConstraints(
                                          maxWidth: MediaQuery.of(context)
                                                  .size
                                                  .width *
                                              0.7),
                                      child: Column(
                                        mainAxisSize: MainAxisSize.max,
                                        children: [
                                          Row(
                                            mainAxisSize: MainAxisSize.max,
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            children: [
                                              Text(
                                                data["msg"],
                                                style: TextStyle(
                                                    color: isSender(
                                                            data["uid"]
                                                                .toString())
                                                        ? Colors.white
                                                        : Colors.black),
                                                maxLines: 100,
                                                overflow:
                                                    TextOverflow.ellipsis,
                                              )
                                            ],
                                          )
                                        ],
                                      )),
                                );
                              }).toList());
                        }
                        return Container(
                          width: 300,
                          height: 300,
                          color: Colors.grey,
                        );
                      })),
              Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Expanded(
                      child: TextField(
                    controller: _controller,
                  )),
                  IconButton(
                      onPressed: () {
                        sendMessage(_controller.text);
                      },
                      icon: Icon(Icons.send))
                ],
              )
            ],
          ),
        ));
  }
}

你能帮帮我吗。谢谢。

0lvr5msh

0lvr5msh1#

此错误可能是由于chatDocId变量在流生成器中使用之前未初始化。在initState方法中,chatDocId变量是在then块中设置的,该块是异步执行的,因此在首次呈现流生成器时可能未初始化该变量。要解决此问题,您可以使用FutureBuilder小部件等待chatDocId变量初始化,然后再呈现流构建器。

相关问题