set<T extends Object?> method

WriteBatch set<T extends Object?>(
  1. DocumentReference<T> documentRef,
  2. T data, [
  3. SetOptions? options
])

Adds a write of data to the document documentRef: the document is created if it does not exist, and replaced if it does.

With options set to SetOptions(merge: true), SetOptions.mergeFields, data is merged into the existing document instead of replacing it. Without options the document is overwritten (SetOptions()).

When documentRef has a converter (withConverter), data is a T and is converted with FirestoreDataConverter.toFirestore; otherwise it is a map of fields to values.

batch.set(
  firestore.doc('cities/SF'),
  <String, Object?>{'capital': false},
  const SetOptions(merge: true),
);

Throws an ArgumentError if data holds a value Firestore cannot store or a FieldValue where it is not allowed (for example FieldValue.delete without a merge), or if documentRef belongs to another FirebaseFirestore instance. Throws a StateError if the batch was already committed.

Returns this batch, so that calls can be chained.

Implementation

WriteBatch set<T extends Object?>(
  DocumentReference<T> documentRef,
  T data, [
  SetOptions? options,
]) {
  final SetOptions? userOptions = options;
  options ??= const SetOptions();
  _firestore.validateReference(documentRef);
  checkNotNull<Object>(data, 'Provided data must not be null.');
  _verifyNotCommitted();
  final Map<String, Object?> rawData = toRawData<T>(
    data,
    documentRef.converter,
    userOptions,
  );
  final UserDataParsedSetData parsed = options.merge
      ? _firestore.dataConverter.parseMergeData(
          rawData,
          options.fieldMask,
          methodName: 'WriteBatch.set',
          targetDoc: documentRef.key,
          hasConverter: documentRef.converter != null,
        )
      : _firestore.dataConverter.parseSetData(
          rawData,
          methodName: 'WriteBatch.set',
          targetDoc: documentRef.key,
          hasConverter: documentRef.converter != null,
        );
  _mutations.add(parsed.toMutation(documentRef.key, Precondition.none));
  return this;
}