如何将对象列表添加到Firestore?

问题描述 投票:0回答:2

我有一个名为customStep的模型,我想将名为customSteps的customStep列表推送到firestore。

这是代码:

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

customSteps集合包含文档,这些文档包含customSteps字段,用于存储customStep数组。但是,此代码将空数组推送到firestore。我该如何解决?

dart flutter google-cloud-firestore
2个回答
0
投票

要将对象推送到Firestore,您需要将对象转换为map,将此函数添加到您的类:

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

要推送一个customSteps列表,您需要将所有对象转换为map,您可以使用以下方法执行此操作:

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

0
投票

在Firebase上,您无法在Document中保存自定义模型

你实际上可以做的是创建一个CustomStep和一个CustomSteps集合。

在你的CustomSteps Document内你可以创建一个arrayReference,这实际上是你的不同CustomStep文件的路径。

Example of a collection

这意味着每次在firestore上创建CustomStep时都会获取id并将其用作对它的引用。

希望能帮助到你 !!

© www.soinside.com 2019 - 2024. All rights reserved.