Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add List of Object to Firestore?

Tags:

I have a model called customStep and I want to push List of customStep called customSteps to firestore.

Here's the code for that:

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

customSteps collection has documents and those documents consist customSteps field to store an array of customStep. However, this code pushes empty array to the firestore. How can I solve it?

like image 330
mirkancal Avatar asked Apr 24 '19 08:04

mirkancal


2 Answers

To push an object to Firestore you need to convert your object to map, add this function to your class:

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

To push a List of customSteps you need to convert all objects to map, you can do it with following method:

  static List<Map> ConvertCustomStepsToMap({List<CustomStep> customSteps}) {
    List<Map> steps = [];
    customSteps.forEach((CustomStep customStep) {
      Map step = customStep.toMap();
      steps.add(step);
    });
    return steps;
  }
like image 54
cipli onat Avatar answered Oct 08 '22 20:10

cipli onat


You need to create an Array of map, like picture below. This map will be your "Object".

So, in your model, you need to declare:

class Model {
   ArrayList<CheckList> checklist = null
}


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

enter image description here enter image description here

like image 37
Jhonatan Sabadi Avatar answered Oct 08 '22 21:10

Jhonatan Sabadi