【问题标题】:Flutter/Dart/Firebase - Updated nested map valuesFlutter/Dart/Firebase - 更新了嵌套地图值
【发布时间】:2021-07-26 04:58:51
【问题描述】:

我正在尝试记录我的用户在我的应用中购买了哪些票。我正在使用 firebase 来存储有关我的用户和赠品的数据。购买完成后,我会尝试更新相关赠品并使用他们的 ID 将每张票分配给用户。

首先,我不确定我的数据架构是否最适合我想要实现的目标,因此我对编辑建议持开放态度,因为我对 Flutter 世界还很陌生。

其次,我的数据目前的结构如下:

这是我构建代码的方式。这是我的 SingleBasketItem 模型:

 class SingleBasketItem {
  final String id;
  final String uid;
  final OurGiveAways giveaway;
  final int ticketNumber;
  SingleBasketItem(this.id, this.uid, this.giveaway, this.ticketNumber);
}

这是我的购物篮模型,我在我的购物篮页面中添加了一个高架按钮,点击该按钮将执行 placeOrder() 函数:

    class ShoppingBasket extends ChangeNotifier {
  Map<String, SingleBasketItem> _items = {};

  Map<String, SingleBasketItem> get items {
    return {..._items};
  }

  void addItem(String id, String uid, OurGiveAways giveaway, int ticketNumber) {
    _items.putIfAbsent(
      id,
      () => SingleBasketItem(id, uid, giveaway, ticketNumber),
    );
    notifyListeners();
  }

  void placeOrder(BuildContext context, OurUser user) {
    for (var i = 0; i < _items.length; i++) {
      FirebaseFirestore.instance
          .collection('giveaways')
          .doc(_items.values.toList()[i].giveaway.giveawayId)
          .update(
        {
          'individual_ticket_sales'[_items.values.toList()[i].ticketNumber]:
              user.uid,
        },
      );
    }
  }
}

下面是结果图片:

通过分析结果,看起来我的代码正在创建一个新字段,其标题为 individual_ticket_sales 的第一个索引字符(“n”,因为我买了票 1),我如何设置嵌套的“1”(或其他我选择的票)到我的用户 ID,而不是创建一个新字段?谢谢。

【问题讨论】:

    标签: firebase flutter dictionary dart google-cloud-firestore


    【解决方案1】:

    我建议重构您的数据库结构,因为您遇到的第一个问题是firestore 目前不支持更新数组字段值的特定索引。你可以得到更多关于here的信息。

    您可以获取整个值 individual_ticket_sales 更新它并再次将其保存为整体,但是当您遇到多个用户想要几乎同时更新相同值的问题时,这只是时间问题,并且其中一项更改丢失了。由于对象的大小和潜在的多次更改,即使使用事务也不是 100% 安全的。

    您是否可以像这样将每个ticketId 存储为firestore document 在firestore collection 中:

    
    FirebaseFirestore.instance
              .collection('giveaways')
              .doc(_items.values.toList()[i].giveaway.giveawayId)
              .collection('individual_ticket_sales')
              .doc(i)
              .update(user.uid);
    

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多