I wrote an article on handling nested objects with Flutter and Firestore and it has some details on how to do this.
Here's my example of retreiving an array, updating it, and saving it back to Firestore:
void AddObjectToArray() {
Exercise exercise;
Set newSet;
Firestore.instance
.collection("exercises")
.document("docID")
.get()
.then((docSnapshot) => {
newSet = Set(10, 30),
exercise = Exercise.fromMap(docSnapshot.data),
exercise.sets.add(newSet),
Firestore.instance.collection("exercises").document("docID").setData(exercise.toMap())
});
}
And my Exercise and Set Classes:
Exercise
class Exercise {
final String name;
final String muscle;
List<dynamic> sets = [];
Exercise(this.name, this.muscle);
Map<String, dynamic> toMap() => {"name": this.name, "muscle": this.muscle, "sets": firestoreSets()};
List<Map<String,dynamic>> firestoreSets() {
List<Map<String,dynamic>> convertedSets = [];
this.sets.forEach((set) {
Set thisSet = set as Set;
convertedSets.add(thisSet.toMap());
});
return convertedSets;
}
Exercise.fromMap(Map<dynamic, dynamic> map)
: name = map['name'],
muscle = map['muscle'],
sets = map['sets'].map((set) {
return Set.fromMap(set);
}).toList();
}
Set
class Set {
final int reps;
final int weight;
Set(this.reps, this.weight);
Map<String, dynamic> toMap() => {"reps": this.reps, "weight": this.weight};
Set.fromMap(Map<dynamic, dynamic> map)
: reps = map["reps"].toInt(),
weight = map["weight"].toInt();
}