Get all from a Firestore collection in Flutter

后端 未结 4 790
一整个雨季
一整个雨季 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条回答
  •  萌比男神i
    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(
            stream: Firestore.instance.collection("expenses").snapshots,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (!snapshot.hasData) return new Text("There is no expense");
              return new ListView(children: getExpenseItems(snapshot));
            });
      }
    
      getExpenseItems(AsyncSnapshot snapshot) {
        return snapshot.data.documents
            .map((doc) => new ListTile(title: new Text(doc["name"]), subtitle: new Text(doc["amount"].toString())))
            .toList();
      }
    }
    

提交回复
热议问题