简体   繁体   English

Firestore 在 Flutter 中返回空列表

[英]Firestore returns empty list in Flutter

I'm having problem in getting data from firestore.I can see all the document exist in firestore collection.But it returns empty list inside stream builder.我在从 firestore 获取数据时遇到问题。我可以看到 firestore 集合中存在所有文档。但它在 stream 构建器中返回空列表。 Here is my code:这是我的代码:

// Chat Screen.Dart

   class ChatScreen extends StatefulWidget {
  static final routeName = "/chat";

  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Inbox"),),
      body: FutureBuilder<String>(
          future: DatabaseService.instance.getUserId(),
          builder: (context, idSnap) {
            if (idSnap.connectionState == ConnectionState.done) {
              print("id snap :${idSnap.data}");
              return StreamBuilder<QuerySnapshot>(
                  stream: DatabaseService.instance.chatListStream(idSnap.data),
                  builder: (context, chatsSnap) {
                    if (chatsSnap.connectionState == ConnectionState.waiting) {
                      return Text("waiting for the data");
                    } else if (chatsSnap.hasError) {
                      return Text('error ${chatsSnap.error}');
                    } else {
                      print("has data");
                      print("document found: ${chatsSnap.data.docs.length}"); // it prints 0 
                      return Text("data is loaded");
                    }
                  });
            } else {
              return Container();
            }
          }
      ),
    );
  }


 
// DatabaseService.dart

class DatabaseService{
 
  DatabaseService._privateConstructor();
  static final DatabaseService instance = DatabaseService._privateConstructor();
  FirebaseFirestore firestore = FirebaseFirestore.instance;

  Future<String>getUserId() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String userId = prefs.getString('user_id') ?? '0';
    return userId;
  }
 
  Stream<QuerySnapshot>chatListStream(String userId){
    return firestore.collection('users').doc(userId).collection('chatList').snapshots();
  }
 
}

I have checked The collection and document title which is correct and the userId being passed is not null and valid data.Here is the Screenshot of firestore database:我检查了正确的集合和文档标题,并且传递的 userId 不是 null 和有效数据。这是 firestore 数据库的屏幕截图:

What am I doing wrong here?我在这里做错了什么?

Look at how the documents in the chatList subcollection(s) are displayed in an italic font: this means that, in the console, these documents are only present as "container" (or "placeholder") of one or more sub-collection(s) but that they are not "genuine" documents, ie they don't exist in the Firestore database.查看chatList子集合中的文档如何以斜体字体显示:这意味着,在控制台中,这些文档仅作为一个或多个子集合的“容器”(或“占位符”)出现( s) 但它们不是“真正的”文档,即它们不存在于 Firestore 数据库中。 Therefore querying documents in one of these chatList subcollections will return an empty QuerySnapshot.因此,在这些chatList子集合之一中查询文档将返回一个空的 QuerySnapshot。

You have probably created documents directly under a sub-collection of each of these chatList documents, without creating the chatList documents themselves.您可能直接在每个这些chatList文档的子集合下创建了文档,而没有创建chatList文档本身。


So, in your case, if you need to have genuine docs in the chatList collections, you need to create them at the same time you create the first subcollection doc.因此,在您的情况下,如果您需要在chatList collections 中有真正的文档,您需要在创建第一个子集合文档的同时创建它们。

Also, note that Cloud Firestore has shallow reads: querying for documents in a collection doesn't pull in data from subcollections.另外,请注意 Cloud Firestore 具有浅读取:查询集合中的文档不会从子集合中提取数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM