How to add server timestamp to firestore document in flutter?

Issue

I am new to firestore. When I try to add a document through the add method within the function addSubject, it throws the error "Expected a value of type ‘String’, but got one of type ‘FieldValue’". I am getting a similar error when I am setting the field to DateTime.now(). How to add the server timestamp to the document?

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

Future<bool> addSubject(FirebaseFirestore x, FirebaseAuth auth, String subjectName) async{
  try {
    var doc = { "subject": subjectName };
    await x.collection('subjects').add(appendCreateAudit(doc, auth));
  } catch (e) {
    print(e);
    return false;
  }
  return true;
}

Map<String, dynamic> appendCreateAudit(Map<String, dynamic> x, FirebaseAuth auth) {
  x["createdAt"] = FieldValue.serverTimestamp();
  x["createdBy"] = auth.currentUser!;
  x["updatedAt"] = FieldValue.serverTimestamp();
  x["updatedBy"] = auth.currentUser!;
  print(x);
  return x;
}

Map<String, dynamic> appendUpdateAudit(Map<String, dynamic> x, FirebaseAuth auth) {
  x["updatedBy"] = auth.currentUser!;
  x["updatedAt"] = FieldValue.serverTimestamp();
  return x;
}

It is possible to send the time stamp as a string, but that is not an optimal solution.

  1. Is there any way one can store timestamp variable in firestore, without first converting it to string?
  2. I am trying to instruct the server to put a timestamp on the field by passing on FieldValue.serverTimestamp(). Can it be done through flutter?

Reference question
Flutter: Firebase FieldValue.serverTimestamp() to DateTime object

Solution

The error was being thrown by this line

x["createdAt"] = FieldValue.serverTimestamp();

Reason: I declared doc as a var

var doc = { "subject": subjectName };

Dart was interpreting doc as Map<String, String > instead of Map <String, dynamic>, hence the error.

Fix:
Map<String, dynamic> doc = { "subject": subjectName };
Working fine now.

Answered By – NewbieCoder

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *