This is a working function I built that adds new Maps to an array in my Firestore Services class. I'm using Json Serializable to annotate all my model classes. userTemplateSections is a data field in my userTemplate firestore documents. I take userTemplate as a constructor of the 'addUserTemplateSection' function to make sure I'm editing the correct document.
I also added the function I made to delete Maps from a firestore document array.
'''
Future<void> addUserTemplateSection(
{UserTemplate userTemplate, String title, String summary}) async {
try {
final UserTemplateSection userTemplateSection =
UserTemplateSection(title: title, summary: summary);
await _firestore
.document(FirestorePath.userTemplate(uid, userTemplate.id))
.updateData(
{
'userTemplateSections':
FieldValue.arrayUnion([userTemplateSection.toJson()])
},
);
} catch (e) {
print(e);
}
}
'''
'''
Future<void> deleteUserTemplateSection({
UserTemplate userTemplate,
UserTemplateSection userTemplateSection,
}) async {
try {
await _firestore
.document(FirestorePath.userTemplate(uid, userTemplate.id))
.updateData(
{
'userTemplateSections':
FieldValue.arrayRemove([userTemplateSection.toJson()])
},
);
} catch (e) {
print(e);
}
}
'''