简体   繁体   English

从 firebase flutter 读取文档和字段

[英]Read Documents and fields from firebase flutter

I have cloud Firestore with one Collection, this collection has many documents and documents have many fields我有一个带有一个集合的云 Firestore,这个集合有很多文档,文档有很多字段

I use stream to get data from the collection and it was work fine but I add some conditions that make my code complex and I didn't understand how to solve it....我使用 stream 从集合中获取数据,它工作正常,但我添加了一些使我的代码复杂的条件,我不明白如何解决它......

if (snapshot.connectionState == ConnectionState.done) {
        DocumentSnapshot doc = snapshot.data!.docs.map((e) =>
            e.data()) as DocumentSnapshot<Object?>;
        Map<String, dynamic> data = doc as Map<String, dynamic>;
        print(data.toString());
      }

I want to know how to read:我想知道如何阅读:

  1. documents in that collection该集合中的文档
  2. field in this documents本文档中的字段

this my code这是我的代码

Widget build(BuildContext context) {
final auth = Provider.of<AuthBase>(context,listen: false);
return StreamBuilder<QuerySnapshot>(
  stream: auth.streamStateChanges()
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {

    }
    if (snapshot.connectionState == ConnectionState.active) {
      

      if (snapshot.connectionState == ConnectionState.done) {
        print(snapshot.data?.docs.map((e) => e.data()));//???????
      }

    }
    return Container();
  });

what should I replace this code I want when ConnectionState.done to return a list of (documents, field) from my collection当 ConnectionState.done 从我的集合中返回(文档、字段)列表时,我应该用什么替换我想要的代码

*===> final _database = FirebaseFirestore.instance.collection('userInfo');
*===> Stream<QuerySnapshot> streamStateChanges() => _database.snapshots();

read field in the specific document读取特定文档中的字段

The document Id of each document must be saved in its field so you can read the specific document data when you get all documents每个文档的文档ID必须保存在其字段中,以便您在获取所有文档时可以读取特定的文档数据

example:例子:

var document = db.collection("collectionName").doc();
var documentId = document.id
document.set({
"documentId":documented,
"otherField": ...,
...,
... })

for get specific field value用于获取特定字段值

db.Collection("collectionName").doc("yourDocumentId").get()
    .then((doc){
print("${doc.get("documentId")}");
});

your stream should be like this你的 stream 应该是这样的

db.Collection("collectionName").doc("yourDocumentId").snapshots();

fore read data like this像这样预先读取数据

snapshot.data["documentId"].toString(),

/////////////////////////////////////////////////////////////////////// ///////////////////////////////////////// ///////////////////

if your stream is return like this:如果您的 stream 是这样返回的:

db.Collection("collectionName").snapshots();

it returns a list of documents so to reach for each document you should use it like that它返回一个文档列表,以便访问您应该像这样使用它的每个文档

switch (snapshot.connectionState) {
   case ConnectionState.none:
     return FutureWidgets.connectionStateNone;
   case ConnectionState.waiting:
     return FutureWidgets.connectionStateWaiting;
   case ConnectionState.active:
     return FutureWidgets.connectionStateActive;
   case ConnectionState.done:
     return ListView(
       padding: const EdgeInsets.all(8),
       children: snapshot.data!.docs.map((document) {
        if(document['someFieldName'] == "someValue")
         {//Todo:do what you want in this document
                 }
         return Text("${document['fieldName'].toString()}");
       }).toList(),
     );
 }
abstract class AuthBase{

  Stream<QuerySnapshot> streamStateChanges();

}

class Auth implements AuthBase {
  final _firebaseAuth = FirebaseAuth.instance;
  final _database = FirebaseFirestore.instance.collection('userInfo');

  @override
  Stream<QuerySnapshot> streamStateChanges() => _database.snapshots();


}

here provider这里提供者

Widget build(BuildContext context) {
    final auth = Provider.of<AuthBase>(context,listen: false);
    return StreamBuilder<QuerySnapshot>(
      stream: auth.streamStateChanges(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

        switch (snapshot.connectionState) {
          case ConnectionState.none:

          case ConnectionState.waiting:

          case ConnectionState.active:
          
          case ConnectionState.done:
            return ListView(
              padding: const EdgeInsets.all(8),
              children: snapshot.data!.docs.map((document) {
                if(document['${auth.currentUser?.uid}'] == auth.currentUser?.uid)
                {//Todo:do what you want in this document
                }
                return Text(document['username'].toString());
              }).toList(),
            );
        }

          //return UserNamePage();

        return Container();
      });
  }

this home screen这个主屏幕

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

相关问题 在 Flutter 上读取从 Firebase 更改的值 - Read values that change from Firebase on Flutter 无法从 Firebase 子集合 Flutter 中获取文档列表 - Not able to get a list of documents from Firebase Subcollection Flutter 使用 2 个变量和 2 个 firebase 字段在 flutter 中过滤来自 firebase 的数据 - filter data from firebase in flutter with 2 variables and 2 firebase fields 使用子 collections >> 子文档从 firebase 文档读取数据 - Read data from firebase document with sub collections >> sub documents React Native Expo:如何使用 Firebase 从集合中的多个文档中查询 select 字段? - React Native Expo: How to query select fields from multiple documents in a collection with Firebase? Flutter Firebase 遍历匹配字段值的所有文档,并将每个文档的字段插入字符串列表 - Flutter Firebase Iterate through all documents that matches field value and inserting field from each one into a List of String 如何在flutter更新firebase的收款文件? - How to update collection documents in firebase in flutter? Firebase 不检索 Flutter 项目中的嵌套集合文档 - Firebase not retrieving nested collection documents in Flutter project 列出子集合中所有文档的名称 - Firebase Flutter - List names of all documents in subcollection - Firebase Flutter 从 flutter 中的 firebase 实时数据库中读取嵌套数据 - Read nested data from firebase realtime database in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM