firebasedartfluttergoogle-cloud-firestore

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


Solution

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