Firestore Field Default Timestamp
2 min readMar 19, 2024
I created a model for the chat message like this.
class Message extends Identifiable {
...
DateTime createdAt;
Message(
{...,
DateTime? createdAt})
: createdAt = createdAt ?? DateTime.now();
I assigned default timestamp now
to createdAt
.
But I’m curious it is possible to set it on server side.
Actually, I am using a function to generate the map to pass in set and update of Firestore.
Map<String, dynamic> toRow() {
return {
MessageFieldNames.authorId: authorId,
MessageFieldNames.authorName: authorName,
MessageFieldNames.content: content
};
}
To order the server set default value to the field, I specified serverTimestamp.
Therefore I checked if createdAt is null and gave server timestamp.
Map<String, dynamic> toRow() {
return {
...
MessageFieldNames.createdAt: createdAt ?? FieldValue.serverTimestamp(),
};
}
Of course I had to make createdAt optional
class Message extends Identifiable {
...
DateTime? createdAt;
Message(
{...,
this.createdAt});
Now I can see creadtedAt
field set by server current timestamp.
If you found this post helpful, please give it a round of applause 👏. Explore more Flutter-related content in my other posts.