繁体   English   中英

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

[英]Get all from a Firestore collection in Flutter

我在我的项目中设置了 Firestore。 我创建了名为categories新集合。 在这个集合中,我创建了三个带有 uniq id 的文档。 现在我想在我的 Flutter 应用程序中获取这个集合,所以我创建了CollectionReference

Firestore.instance.collection('categories')

但我不知道接下来会发生什么。

我正在使用这个插件firebase_firestore: 0.0.1+1

如果您只想阅读一次,这里是代码

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

使用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();
  }
}

这是从我发现有效的集合中获取所有数据的最简单方法,而不使用不推荐使用的方法。

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);
}

我想出了一个解决方案:

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);
  }
}

调用getDocs()函数,我使用了 build 函数,它在控制台中打印了所有文档 ID。

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

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

到 2021 年, cloud_firestore包发生了一些重大变化。 我在一个项目上与 firestore 合作,发现由于 API 更改,旧教程都不起作用。

在阅读了 Stack 上的文档和其他一些答案之后,这里是相同的解决方案。

您需要做的第一件事是为您的收藏创建一个参考。

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

下一步是查询集合。 为此,我们将在集合引用对象上使用get方法。

QuerySnapshot querySnapshot = await _cat.get()

最后,我们需要解析查询快照以从我们集合中的每个文档中读取数据。 在这里,我们将每个文档解析为地图(字典)并将它们推送到列表中。

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

整个函数看起来像这样:

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

对我来说,它适用于 cloud_firestore 版本 ^2.1.0

这是以 JSON 形式显示每个集合的简单代码。 我希望这会帮助某人

FirebaseFirestore.instance.collection("categories").get().then(
  (value) {
    value.docs.forEach(
      (element) {
        print(element.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. }
  • 监听所有数据:

     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. } });

如果您将数据存储在文档 Id 中呢? 如果文档为空,则无法获取 id 文档,这是一个错误,除非您在特定文档中设置字段

在此处输入图片说明

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);
}

从 Firestore 检索数据的最简单方法是:

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