flutter - 使用 Firebase 是否可以防止两个人同时将产品添加到购物车?

标签 flutter firebase dart google-cloud-firestore

我正在使用 Firebase DB 和 Flutter 导入产品目录。只有 1 人可以将产品添加到购物车。如果 2 人或更多人想同时将产品添加到购物篮,则该产品将添加到所有人中。我该怎么做才能取回它?

  void addBasket(Map<String, dynamic> data, index) async {

    var _storage = await GetStorage();

    final CollectionReference user_basket =
        await FirebaseFirestore.instance.collection('user basket');
    final CollectionReference product =
        await FirebaseFirestore.instance.collection('product');
    final DocumentReference ref = await product.doc(data['id']);
    await FirebaseFirestore.instance.runTransaction((Transaction tx) async {
      DocumentSnapshot snap = await tx.get(ref);
      if (snap.exists) {
       await product.doc(data['id']).delete();
        await tx.update(ref, data);


      await  user_basket
            .doc(_storage.read('uid'))
            .collection('basket')
            .doc(data['id'])
            .set(data);
        inArea.removeAt(index);
        Get.back();
        Get.back();
      } else {
      await  user_basket
            .doc(_storage.read('uid'))
            .collection('basket')
            .doc(data['id'])
            .delete();
        Get.back();
        Get.defaultDialog(
            title: "Wrong",
            middleText:
                "This product is being reviewed by another person.");
      }
    });
  }

我尝试使用事务,正如您在代码中看到的那样。我第一次编写这段代码时对其进行了测试。当两个人同时按下按钮时,两人中的一个可以将产品添加到购物车。我今天想再测试一下。我按下了将产品添加到购物车按钮,结果 If 和 Else 博客都起作用了。所以我开始出现错误。我想要得到的确切结果是,当超过 1 个人想要将相同的产品添加到购物车时,会得到相反的结果。让第一次单击按钮将产品添加到购物篮中,其他人将通过 Alerd 对话框收到通知。

最佳答案

我相信您正在客户端之间创建竞争条件。在 Firestore 的所有实现中,我没有对 collectionquery 引用使用 await。您应该只需要 await get() 方法本身。

当您查看 Flutter Firestore 文档以了解其事务实现时,您会发现它们不会等待顶部的集合引用。

https://firebase.google.com/docs/firestore/manage-data/transactions#dart

而不是:

final CollectionReference user_basket =
    await FirebaseFirestore.instance.collection('user basket');
final CollectionReference product =
    await FirebaseFirestore.instance.collection('product');
final DocumentReference ref = await product.doc(data['id']);

尝试使用:

final CollectionReference user_basket = FirebaseFirestore.instance.collection('user basket');
final CollectionReference product = FirebaseFirestore.instance.collection('product');
final DocumentReference ref = product.doc(data['id']);

希望有帮助!我将尝试制作一个 Firestore 事务演示,看看是否可以复制并解决您所描述的问题。

关于flutter - 使用 Firebase 是否可以防止两个人同时将产品添加到购物车?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75353429/

相关文章:

dart - 如何在网页 View 中实现进度指示器?

dart - Flutter-来自WebViewScaffold中显示的网页的电话调用

Flutter 检查 Uint8List 是否有效 Image

Flutter 问题 - 来自 sdk 的 Flutter_driver 依赖于文件 5.0.6 而 flutter_gallery 依赖于文件 5.0.7

bash - 您如何在当前进程中使用 dart.io 获取 shell 脚本?

dart - dart 是否支持客户端 SSL/TLS 连接?

android - 使用 Firebase 的最低 Google Play 服务版本是多少?

firebase - Flutter - 从 firestore 循环获取数据

Swift - 从 Firebase 检索自动分配的 ID

android - 更新包后 Flutter Android 构建失败。安卓X错误