首页 > 解决方案 > 无法使用 Flutter 从 Firestore 检索文档

问题描述

.. 我正在将 Cloud Firestore 用于我正在进行的 Flutter 项目。

数据库截图

上面添加的是我的数据库模型的屏幕截图。

基本上每个用户文档都有自己的个人信息字段和他/她的项目的集合。

项目示例 1

项目示例 2

以上是两个扩展项目的截图。它具有项目的详细信息,例如其 CR、字段、成员等。

 x = StreamBuilder(
          stream: _projectStreamLock ? null : Firestore.instance.collection('User').document(_savedUser.user.uid).collection('Projects').snapshots(),
          builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshots){
            if(snapshots.hasData && !_projectStreamLock){

              List<DocumentSnapshot> projectList = snapshots.data.documents;

              _savedUser.user.projects = [];

              for(int i=0;i<projectList.length;i++){
                _savedUser.user.projects.add(Project(name: projectList[i].documentID,field: projectList[i].data["Field"],subField: projectList[i].data["SubField"],completionRate: projectList[i].data["CR"],members: projectList[i].data["Members"]));
              }

              return ListView.builder(
                  itemCount: snapshots.data.documents.length,
                  itemBuilder: (_,int index){
                    print(snapshots.data.documents[index].documentID + " : " + snapshots.data.documents[index].data["CR"].toString());
                    return ProjectCard(
                      globalHeight: _height,globalWidth: _width,
                      projectDetails: Project(
                          name : snapshots.data.documents[index].documentID,
                          completionRate: snapshots.data.documents[index].data["CR"],
                          field: snapshots.data.documents[index].data["Field"],
                          members: snapshots.data.documents[index].data["Members"],
                          subField: "Hello",
                      ),
                    );
                  });
              ///
            }
            else{
              _projectStreamLock = false;
              return ListView.builder(
                //  key: new Key(Random.secure().nextDouble().toString()),
                  itemCount: _savedUser.user.projects.length,
                  itemBuilder: (_,int index){
                    return ProjectCard(globalHeight: _height,globalWidth: _width,projectDetails: _savedUser.user.projects[index],);
                  });
            }
          },
        );

上面是创建代表每个项目的卡片列表的代码。代码可能看起来有点乱,但请在第一个“if”案例中关注 ListView.builder Widget。在以下代码片段中,我从快照中提取数据并创建每个项目的项目对象。

我面临的问题是,在获取第一个项目(E-Cell App)的 CR 值时。我得到一个空值。但我得到了所有其他项目的正确 CR 值。正如您在代码片段中看到的那样,我正在打印列表中添加的每个项目的名称 (documentID) 和 CR。下面是输出。

打印语句输出

如仅第一个项目(E-Cell App)的输出 CR 值为空。不包括我得到了所有其他项目的正确价值。我不确定是什么导致了这个问题。在所有项目中,CR 采用相同的格式(数字)。正如上面发布的图片“项目示例 1”是提供空 CR 值的图片,“项目示例 2”提供正确的 CR 值,就像所有其他项目一样。在此先感谢您的帮助。

标签: flutterdartgoogle-cloud-firestore

解决方案


你犯了我几天前犯的同样的错误。

您在“E-Cell”文档的字段名称中添加了一个空格

对于 Firestore , “Cr”“Cr”是不同的字段。

注意第一个空间很小,很难指出。

此外,自从我加入 stack-overflow 已经有几天了,您在问题中包含的信息对我发现错误有很大帮助。您的问题无疑是其他人的榜样。


推荐阅读