使用此代码时我没有得到任何数据,我注意到当我执行。doc()而不是。where()
时,此代码可以工作。如何使where子句与map方法一起工作
new StreamBuilder(
stream: FirebaseFirestore.instance.collection("purchasedItems").where('paymentID', isEqualTo: "Jdc2kAoMVQq0AfcoS0uO").snapshots().map(DatabaseService().purchasedItemfromSnapshot),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Container();
}
List<PurchasedItem> items = snapshot.data.docs;
return ListView.builder(...)
})
map函数:
List<PurchasedItem> purchasedItemfromSnapshot (QuerySnapshot snapshot){
return snapshot.docs.map((doc){
var data = doc.data() as Map<String, dynamic>;
return PurchasedItem(
purchasedItemID: doc.id,
paymentID: data['paymentID'],
purchasedItemName: data['purchasedItemName'],
price: data['price'],
purchasedItemCurrency: data['purchasedItemCurrency']
);
}).toList();
}
snapshot.data.docs
中没有docs
实例
直接赋值List<PurchasedItem> items = snapshot.data
除此之外,你的代码应该可以工作。这是使用Stream
的另一种方法。试试这个方法。
流函数
Stream<List< PurchasedItem>> getItems(String id) {
var ref = _db.collection('purchasedItems').where('paymentID', isEqualTo: id);
return ref.snapshots().map((list) => list.docs.map((doc) => PurchasedItem.fromFirestore(doc)).toList());
}
模型类
class PurchasedItem {
final String purchasedItemID, purchasedItemName;
PurchasedItem({this.purchasedItemID,this.purchasedItemName});
factory PurchasedItem.fromFirestore(DocumentSnapshot doc) {
Map data = doc.data();
return PurchasedItem(
purchasedItemID: doc.id,
//paymentID: data['paymentID'],
purchasedItemName: data['purchasedItemName'],
//price: data['price'],
//purchasedItemCurrency: data['purchasedItemCurrency']
);}
}
StreamBuilder部件
StreamBuilder<List<PurchasedItem>>(
stream: getItems('Jdc2kAoMVQq0AfcoS0uO'),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Container();
}
return ListView.builder(
itemCount: snapshot?.data?.length ?? 0,
itemBuilder:(_, int index) {
final PurchasedItem data = snapshot.data[index];
return Text(data.purchasedItemName);
}
);
})