Kamil Harasimowicz
Kamil Harasimowicz

Reputation: 5004

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

Upvotes: 39

Views: 106090

Answers (11)

Sakib Shaikh
Sakib Shaikh

Reputation: 17

Fetching everything from a collection.

Add collection names in list in the field section. Fetch that field data first. Then pass the field data to fetch the collection.

enter image description here

Upvotes: -1

Jalal W Bradosty
Jalal W Bradosty

Reputation: 11

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

Upvotes: 1

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

Upvotes: 0

Aman Sharma
Aman Sharma

Reputation: 175

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
}

Upvotes: 8

CopsOnRoad
CopsOnRoad

Reputation: 268494

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

Upvotes: 7

Shahid Bangash
Shahid Bangash

Reputation: 41

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

Upvotes: 3

breberaf
breberaf

Reputation: 796

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

Upvotes: 62

Stelio Braga
Stelio Braga

Reputation: 61

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

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

Upvotes: 6

Ron
Ron

Reputation: 271

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.

Upvotes: 13

Tree
Tree

Reputation: 31431

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

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

Upvotes: 38

Putra Ardiansyah
Putra Ardiansyah

Reputation: 5883

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

Upvotes: 34

Related Questions