簡體   English   中英

如何將對象列表添加到 Firestore?

[英]How to add List of Object to Firestore?

我有一個名為customStep的模型,我想將名為customSteps的 customStep 列表推送到 firestore。

這是代碼:

Firestore.instance
    .collection('customSteps')
    .add({'customSteps': customSteps});

customSteps 集合有文檔,這些文檔由 customSteps 字段組成,用於存儲 customStep 數組。 但是,此代碼將空數組推送到 firestore。 我該如何解決?

要將對象推送到 Firestore,您需要將對象轉換為映射,將此函數添加到您的類中:

  Map<String, dynamic> toMap() {
    return {
      'yourField1': yourValue1,
      'yourField2': yourValue1,
    };
  }

要推送自定義步驟列表,您需要將所有對象轉換為地圖,您可以使用以下方法完成:

  static List<Map> ConvertCustomStepsToMap({List<CustomStep> customSteps}) {
    List<Map> steps = [];
    customSteps.forEach((CustomStep customStep) {
      Map step = customStep.toMap();
      steps.add(step);
    });
    return steps;
  }

您需要創建一個地圖數組,如下圖所示。 這張地圖將是您的“對象”。

因此,在您的模型中,您需要聲明:

class Model {
   ArrayList<CheckList> checklist = null
}


class CheckList implements Serializable {
        String item = null,
        boolean isChecked = false
} 

在此處輸入圖像描述 在此處輸入圖像描述

在 Firebase 上,您無法將自定義模型保存在Document

您實際上可以做的是創建一個CustomStep和一個CustomSteps集合。

在您的CustomSteps Document中,您可以創建一個Reference array ,它實際上是您不同的CustomStep文檔的路徑。

集合示例

這意味着每次在 firestore 上創建CustomStep時獲取 id 並將其用作參考。

希望能幫助到你 !!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM