简体   繁体   English

从 Flutter 中的 Firestore 集合中获取所有内容

[英]Get all from a Firestore collection in Flutter

I set up Firestore in my project.我在我的项目中设置了 Firestore。 I created new collection named categories .我创建了名为categories新集合。 In this collection I created three documents with uniq id.在这个集合中,我创建了三个带有 uniq id 的文档。 Now I want to get this collection in my Flutter application so I created CollectionReference :现在我想在我的 Flutter 应用程序中获取这个集合,所以我创建了CollectionReference

Firestore.instance.collection('categories')

but I don't know what next.但我不知道接下来会发生什么。

I am using this plugin firebase_firestore: 0.0.1+1我正在使用这个插件firebase_firestore: 0.0.1+1

Here is the code if you just want to read it once如果您只想阅读一次,这里是代码

   QuerySnapshot querySnapshot = await Firestore.instance.collection("collection").getDocuments();
    var list = querySnapshot.documents;

Using StreamBuilder使用StreamBuilder

import 'package:flutter/material.dart';
import 'package:firebase_firestore/firebase_firestore.dart';

class ExpenseList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance.collection("expenses").snapshots,
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) return new Text("There is no expense");
          return new ListView(children: getExpenseItems(snapshot));
        });
  }

  getExpenseItems(AsyncSnapshot<QuerySnapshot> snapshot) {
    return snapshot.data.documents
        .map((doc) => new ListTile(title: new Text(doc["name"]), subtitle: new Text(doc["amount"].toString())))
        .toList();
  }
}

This is the easiest way to get all data from collection that I found working, without using deprecated methods.这是从我发现有效的集合中获取所有数据的最简单方法,而不使用不推荐使用的方法。

CollectionReference _collectionRef =
    FirebaseFirestore.instance.collection('collection');

Future<void> getData() async {
    // Get docs from collection reference
    QuerySnapshot querySnapshot = await _collectionRef.get();

    // Get data from docs and convert map to List
    final allData = querySnapshot.docs.map((doc) => doc.data()).toList();

    print(allData);
}

I was able to figure out a solution:我想出了一个解决方案:

Future getDocs() async {
  QuerySnapshot querySnapshot = await Firestore.instance.collection("collection").getDocuments();
  for (int i = 0; i < querySnapshot.documents.length; i++) {
    var a = querySnapshot.documents[i];
    print(a.documentID);
  }
}

Call the getDocs() function, I used build function, and it printed all the document IDs in the console.调用getDocs()函数,我使用了 build 函数,它在控制台中打印了所有文档 ID。

QuerySnapshot snap = await 
    Firestore.instance.collection('collection').getDocuments();

snap.documents.forEach((document) {
    print(document.documentID);
  });

As of 2021, there have been some major changes in the cloud_firestore package.到 2021 年, cloud_firestore包发生了一些重大变化。 I was working with firestore on a project, and found that none of the old tutorials were working due to the API changes.我在一个项目上与 firestore 合作,发现由于 API 更改,旧教程都不起作用。

After going through documentation and a few other answers on Stack, here's the solution for the same.在阅读了 Stack 上的文档和其他一些答案之后,这里是相同的解决方案。

The first thing that you need to do is create a reference for your collection.您需要做的第一件事是为您的收藏创建一个参考。

CollectionReference _cat = FirebaseFirestore.instance.collection("categories");

Next step is to query the collection.下一步是查询集合。 For this, we will be using the get method on the collection reference object.为此,我们将在集合引用对象上使用get方法。

QuerySnapshot querySnapshot = await _cat.get()

Finally, we need to parse the query snapshot to read the data from each document within our collection.最后,我们需要解析查询快照以从我们集合中的每个文档中读取数据。 Here, we will parse each of the documents as maps (dictionaries) and push them to a list.在这里,我们将每个文档解析为地图(字典)并将它们推送到列表中。

final _docData = querySnapshot.docs.map((doc) => doc.data()).toList();

The entire function will look something like this:整个函数看起来像这样:

getDocumentData () async {
    CollectionReference _cat = FirebaseFirestore.instance.collection("categories");
    final _docData = querySnapshot.docs.map((doc) => doc.data()).toList();
    // do any further processing as you want
}

For me it works on cloud_firestore version ^2.1.0对我来说,它适用于 cloud_firestore 版本 ^2.1.0

Here is the simple code to display each colection in JSON form.这是以 JSON 形式显示每个集合的简单代码。 I hope this would help someone我希望这会帮助某人

FirebaseFirestore.instance.collection("categories").get().then(
  (value) {
    value.docs.forEach(
      (element) {
        print(element.data());
      },
    );
  },
);

Update:更新:

  • One time read of all data:一次性读取所有数据:

     var collection = FirebaseFirestore.instance.collection('users'); var querySnapshot = await collection.get(); for (var doc in querySnapshot.docs) { Map<String, dynamic> data = doc.data(); var fooValue = data['foo']; // <-- Retrieving the value. }
  • Listening for all data:监听所有数据:

     var collection = FirebaseFirestore.instance.collection('users'); collection.snapshots().listen((querySnapshot) { for (var doc in querySnapshot.docs) { Map<String, dynamic> data = doc.data(); var fooValue = data['foo']; // <-- Retrieving the value. } });

what If you store data in the docs Id ?如果您将数据存储在文档 Id 中呢? if the doc is EMPTY, it would be IMPOSSIBLE to get the id doc, its a bug, unless you set a field in a specific doc如果文档为空,则无法获取 id 文档,这是一个错误,除非您在特定文档中设置字段

enter image description here在此处输入图片说明

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

final database1 = FirebaseFirestore.instance;
Future<QuerySnapshot> years = database1
  .collection('years')
  .get();

class ReadDataFromFirestore extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return FutureBuilder<QuerySnapshot>(
        future: years,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final List<DocumentSnapshot> documents = snapshot.data.docs;
            return ListView(
                children: documents
                    .map((doc) => Card(
                          child: ListTile(
                        title: Text('doc.id: ${doc.id}'),
                            //subtitle: Text('category:     ${doc['category']}'),
                      ),
                    ))
                .toList());
      } else if (snapshot.hasError) {
        return Text(snapshot.error);
      }
      return CircularProgressIndicator();
    }
    );
  }
}
final _fireStore = FirebaseFirestore.instance;
Future<void> getData() async {
    // Get docs from collection reference
    QuerySnapshot querySnapshot = await _fireStore.collection('collectionName').get();

    // Get data from docs and convert map to List
    final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
  //for a specific field
  final allData =
          querySnapshot.docs.map((doc) => doc.get('fieldName')).toList();

    print(allData);
}

the easiest way of retrieve data from the firestore is:从 Firestore 检索数据的最简单方法是:

void getData() async { await for (var messages in _firestore.collection('collection').snapshots()) { for (var message in messages.docs.toList()) { print(message.data()); void getData() async { await for (var messages in _firestore.collection('collection').snapshots()) { for (var message in messages.docs.toList()) { print(message.data()); } } } } } }

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

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