33

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

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
Kamil Harasimowicz
  • 4,684
  • 5
  • 32
  • 58

10 Answers10

58

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);
}
breberaf
  • 636
  • 5
  • 5
  • 4
    As of 2021, this is the working solution. – Terblanche Daniel Jan 27 '21 at 15:08
  • 1
    finally! every answer had deprecated methods, but this worked perfectly, thank you. – hewa jalal Feb 20 '21 at 12:22
  • I think the problem here is we are thinking imperatively instead of declaratively here. When something changes on either end, we want to have that reflected, right? This is what makes a 'real-time database.' Using this implementation, we have effectively cut out the ability to stream back and forth changes. This is no longer declarative ! – Gene Feb 23 '21 at 15:17
  • 1
    I agree with you. There are solutions like streambuilders, mobx or other reactivity libraries to keep your database real-time. However, for people who doesn’t need the functionality of real-time updates, this solution works just fine. – breberaf Feb 24 '21 at 21:47
36

Here is the code if you just want to read it once

   QuerySnapshot querySnapshot = await Firestore.instance.collection("collection").getDocuments();
    var list = querySnapshot.documents;
Tree
  • 29,135
  • 24
  • 78
  • 98
32

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();
  }
}
Putra Ardiansyah
  • 5,249
  • 4
  • 25
  • 37
  • Yeah. I saw this example in plugin doc. In my case I want to load whole collection to Dart array without creating widgets. Is it possible? – Kamil Harasimowicz Oct 06 '17 at 20:47
  • I've tried this one, listen to value ``Firestore.instance.collection("expenses").snapshots.listen((snapshot) { snapshot.documents.forEach((doc) => debugPrint(doc.data.toString())); });`` – Putra Ardiansyah Oct 06 '17 at 20:54
  • How it works. Code in block will indicate every time collection change? Should I stop listening? Is is possible to read this date once? – Kamil Harasimowicz Oct 06 '17 at 20:57
  • Yes. It seems listener will automatically removed when there is no subscriber. Unfortunately there is no ``single value listener`` on its native api plugin – Putra Ardiansyah Oct 06 '17 at 21:20
  • You should be able to `await` on `snapshots.first` to get one `QuerySnapshot`. – Collin Jackson Oct 07 '17 at 11:06
  • I found out it doesn't work when using multiple orderBy, any ideas why? Example. `stream: Firestore.instance.collection("expenses").orderBy('createdAt').orderBy('title').snapshots` – devnomic Mar 25 '18 at 20:59
  • have you added order index in your collection? – Putra Ardiansyah Mar 25 '18 at 21:37
  • This is very expensive - it listens to all changes for the entire collections and likely returns more data than you need. Use with caution if you have a large collection – E. Sun Feb 01 '20 at 20:34
12

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.

Ron
  • 261
  • 4
  • 6
7

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
}

Aman Sharma
  • 165
  • 1
  • 6
6

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.
      }
    });
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
5
QuerySnapshot snap = await 
    Firestore.instance.collection('collection').getDocuments();

snap.documents.forEach((document) {
    print(document.documentID);
  });
Stelio Braga
  • 51
  • 2
  • 4
2

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());
      },
    );
  },
);
1

the easiest way to 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()); 
            }
        }
    }
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 04 '21 at 07:34
  • 1
    replace _firestore. with FirebaseFirestore.instance. – Jan Dec 11 '21 at 22:56
0

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