【问题标题】:Firestore - add array of objectsFirestore - 添加对象数组
【发布时间】:2021-05-26 19:17:40
【问题描述】:

我在将对象数组(表)添加到对象数组(餐厅)时遇到了麻烦。我的意思是,我有以下 Firestore 结构:

... (other data)
restaurants: [
   0: {
      name: name_0
      ...
      tables: [
          0: { no_chairs: 5, ... },
      ]
   },
   ...
]

我知道如何向餐馆添加新对象,但如果表列表包含任何数据,我在添加新餐馆时遇到问题。

我的代码:

    var collection = firestore.collection('usersData')
        .doc(this.currentUser.uid).collection('buisness').doc('restaurants');
    collection.update({
      'restaurants': FieldValue.arrayUnion([restaurant.toJson()]),
    }).then( ... // reaction based on api answer
class Restaurant:
     Map<String, dynamic> toJson() => {
    'name': name,
    ...
    'tables': tables!=null? [tables] : [], // I think that I should modify this line
  };

class Table:
    Map<String, dynamic> toJson()=> { // Or this method / use another
    'no_chairs': no_chairs,
    ...
  };

有什么简单的方法吗?最好不要修改firestore文件结构,但如果有必要我愿意这样做。


补充问题: 如何修改表格列表中的对象?比如我想把 no_chairs 改成 7

【问题讨论】:

    标签: android firebase flutter


    【解决方案1】:

    从你上面的代码来看,下面这行有问题:

    'tables': tables!=null? [tables] : [], 
    

    这部分[tables] 表示您将列表tables 作为外部列表的一个元素。

    为了说明,如果tables如下图所示:

    List<int> tables = [1, 2, 3];
    

    那么,[tables] 是这样的:

    [[1, 2, 3]]
    

    解决方案:

    您可以直接使用tables 变量,因为您要发送一个列表。

    在发送您的tables 对象之前,您需要将其从当前的TableModel 列表转换为地图列表(根据您在下面的评论)。

    所以你可以修改你的代码:

    'tables': tables != null ? tables.map((TableModel table) => table.toJson()).toList() : [], 
    

    额外问题:如何修改表列表中的对象?例如我 想把 no_chairs 改成 7

    解决方案: 您必须获取实际的餐馆列表并修改您想要的确切表对象并将修改后的列表设置为 Firestore。

     var collection = firestore.collection('usersData').doc(this.currentUser.uid).collection('buisness').doc('restaurants');
    
     //Get list of restaurants
     List<Restaurant> restaurantList = ((await collection.get()).data()).map((dynamic restaurantJson) => Restaurant.fromJson(restaurantJson)).toList();
    
     Set number of chairs
     //
     restaurantList[restaurantIndex].tables[tableIndex].no_chairs = 7; //This assumes the no_chairs field is not final
    
     //Set list 
     collection.set({
       "restaurants": restaurantList.toJson()
     })
    
    

    【讨论】:

    • 没有 [] 我收到错误:无法添加餐厅:无效参数:“TableModel”实例作为来自 firebase 的响应
    • 好的,我会针对这个问题进行更新。
    • @next_99,请查看更新后的答案。
    • 效果很好。您还可以帮助解决额外的问题吗? - 编辑值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2021-08-24
    • 1970-01-01
    • 2020-12-28
    • 2020-08-06
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多