Reputation: 67
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.
Reference question Flutter: Firebase FieldValue.serverTimestamp() to DateTime object
Upvotes: 4
Views: 1146
Reputation: 67
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.
Upvotes: 0
Reputation: 72
The value that you are sending is not of the type String
. Simply convert it woth toString()
before sending and it will fix the error.
Example:
FieldValue.serverTimestamp().toString();
or just:
"${FieldValue.serverTimestamp()}";
Upvotes: 0