【发布时间】:2019-12-26 09:25:43
【问题描述】:
我正在尝试使用 Flutter 和 Firestore 构建电子商务应用,但在构建购物车方面遇到了挑战。使用下面的代码,我已经能够使用产品 ID 获取用户希望添加到购物车的产品。我的挑战是如何使用 id 或键从 Firestore 获取产品的详细信息并将购物车产品存储在 Firestore 或 SQLite 中,以便我可以从那里查询并将它们显示在购物车页面上。
appstate.dart
class AppStateModel extends Model {
final Map<int, int> _productsInCart = <int, int>{};
Map<int, int> get productsInCart => Map<int, int>.from(_productsInCart);
void addProductToCart(int productId) {
if (!_productsInCart.containsKey(productId)) {
_productsInCart[productId] = 1;
} else {
_productsInCart[productId]++;
}
notifyListeners();
}
void removeItemFromCart(int productId) {
if (_productsInCart.containsKey(productId)) {
if (_productsInCart[productId] == 1) {
_productsInCart.remove(productId);
} else {
_productsInCart[productId]--;
}
}
notifyListeners();
}
void clearCart() {
_productsInCart.clear();
notifyListeners();
}
}
product_display.dart 具有 onPressed 功能的页面,用于获取点击添加到购物车的商品的 id
CupertinoActionSheetAction(
child: const Text('Add To Cart'),
onPressed: () {
model.addProductToCart(products[index].id);
},
)
product.dart
class Products{
final String category;
final String description;
final int id;
final int price;
final String title;
final String url;
const Products( {this.category,this.description,this.id, this.price, this.title, this.url,
});
}
CartProduct.dart
class CartProducts{
final String category;
final String description;
final int id;
final int price;
final String title;
final String url;
const CartProducts( {this.category,this.description,this.id, this.price, this.title, this.url,
});
}
现在假设我在产品购物车中有 id 为 1、4、6、9、11 的产品,当我使用 print(model.productsInCart.keys) 在控制台中打印时,这是输出 (1、4、6 , 9, 11),现在我的挑战是如何使用这些 id 从 Firestore 集合产品中查询 id 为 1、4、6、9、11 的产品,并将它们存储在 Firebase 或 SQLite 中,以便我可以在购物车页面供用户查看他/她在购物车中的物品。
【问题讨论】:
标签: flutter google-cloud-firestore shopping-cart