saveDocument method

  1. @override
Future<void> saveDocument(
  1. String collection,
  2. Map<String, dynamic> data
)
override

Saves a document to Firestore.

This method checks if the provided data contains an 'id' field. If it does, it updates the existing document with that ID in the Firestore collection. If not, it creates a new document with an automatically generated ID.

collection: The name of the Firestore collection. data: A Map containing the document data to be saved.

Returns a Future that resolves when the document is saved.

Implementation

@override
Future<void> saveDocument(String collection, Map<String, dynamic> data) {
  // Determine if the document should be updated or created
  final docRef = data.containsKey('id')
      ? FirebaseFirestore.instance
          .collection(collection)
          .doc(data['id']) // Update existing document
      : FirebaseFirestore.instance
          .collection(collection)
          .doc(); // Create a new document

  // Save the document data, using merge to preserve existing fields if the document exists
  return docRef.set(data, SetOptions(merge: true));
}