无法将参数类型“QueryDocumentSnapshot”分配给参数类型“AsyncSnapshot<dynamic>”

时间:2021-01-09 09:32:48

标签: firebase flutter google-cloud-firestore firebase-authentication

我尝试使用 for 快照循环从 firestore 获取数据,但出现错误。

这是我的代码:

Future<List<Product>> getProducts() => _firestore
  .collection(collection)
  .where('show', isEqualTo: true)
  .get()
  .then((snap) {
List<Product> products = [];
for (int i = 0; i < snap.docs.length; i++) {
  products.add(Product.fromSnapshot(snap.docs[i]));
}
return products;
});

错误在 (snap.docs[i]]。

2 个答案:

答案 0 :(得分:0)

似乎 Product.fromSnapshot() 想要一个 AsyncSnapshotStreamBuilderFutureBuilder 使用的 Flutter 类),但你给它一个 QueryDocumentSnapshot,它是一个 Firebase班级。我的猜测是您想更改该函数的参数类型。

答案 1 :(得分:0)

推荐的方式是使用FlutterFire

获取数据的一个简单示例是:

FirebaseFirestore.instance
    .collection('products')
    .get()
    .then((QuerySnapshot querySnapshot) => {
        querySnapshot.docs.forEach((doc) {
            print(doc["name"]);
        });
    });