简体   繁体   中英

Get all from a Firestore collection in Flutter

I set up Firestore in my project. I created new collection named categories . In this collection I created three documents with uniq id. Now I want to get this collection in my Flutter application so I created CollectionReference :

Firestore.instance.collection('categories')

but I don't know what next.

I am using this plugin 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

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.

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. I was working with firestore on a project, and found that none of the old tutorials were working due to the API changes.

After going through documentation and a few other answers on Stack, here's the solution for the same.

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.

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

Here is the simple code to display each colection in JSON form. 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 ? 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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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