【发布时间】:2020-10-15 18:30:40
【问题描述】:
我正在尝试从 Firestore 加载我的所有产品数据。我有一个数据架构:
class SingleProduct with ChangeNotifier {
static const EVENT = "event";
static const IMGURL = "imgUrl";
static const NAME = "name";
static const PRICE = "price";
//Private Variables
String _event;
String _imgUrl;
String _name;
double _price;
// getters
String get event => _event;
String get imgUrl => _imgUrl;
String get name => _name;
double get price => _price;
SingleProduct.fromSnapshot(DocumentSnapshot snapshot) {
_event = snapshot.data()[EVENT];
_imgUrl = snapshot.data()[IMGURL];
_name = snapshot.data()[NAME];
_price = snapshot.data()[PRICE];}
}
然后我创建了一个类来将收到的所有数据映射到产品列表:
class ProductServices {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
String collection = 'products';
Future<List<SingleProduct>> getAllProducts() async =>
_firestore.collection(collection).get().then((snap) {
print(snap.docs.length); // returns 11 products as expected
List<SingleProduct> allProducts = [];
snap.docs.map((snapshot) =>
allProducts.add(SingleProduct.fromSnapshot(snapshot)));
print(allProducts.length); //returns 0 so I think my map isn't working
return allProducts;
});
}
Firestore 查询按预期返回 11 个查询快照,但我随后尝试使用我的产品架构将它们添加到列表中,但结果显示该列表有 0 个元素。有什么建议如何将我的火基查询的结果映射到列表?
【问题讨论】:
-
请编辑问题以解释究竟是什么不符合您的预期。我们真的不知道问题是什么。
标签: firebase flutter google-cloud-firestore