Get all from a Firestore collection in Flutter

后端 未结 4 777
一整个雨季
一整个雨季 2020-12-08 16:28

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 c

相关标签:
4条回答
  • 2020-12-08 17:05

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

       QuerySnapshot querySnapshot = await Firestore.instance.collection("collection").getDocuments();
        var list = querySnapshot.documents;
    
    0 讨论(0)
  • 2020-12-08 17:06

    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.

    0 讨论(0)
  • 2020-12-08 17:07
    QuerySnapshot snap = await 
        Firestore.instance.collection('collection').getDocuments();
    
    snap.documents.forEach((document) {
        print(document.documentID);
      });
    
    0 讨论(0)
  • 2020-12-08 17:12

    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();
      }
    }
    
    0 讨论(0)
提交回复
热议问题