如何从Flutter将文档创建的时间戳添加到Firestore [英] How to add timestamp on document create to Firestore from Flutter
问题描述
我正在编写代码,以将数据设置为从flutter传递到Firestore.我想要的是在创建数据时添加一个字段,例如"createdOn".Flutter的DateTime.now()从设备获取时间,但是我想获取服务器端时间.我的代码如下:
I am writing code to set data to Firestore from flutter. What I want is to add a field for the time the data is created, eg "createdOn". DateTime.now() for Flutter takes the time from the device but I would like to get the serverside time. My code is as below:
Future updateDataModel(String userName, String userPosition, String userLocation) async{
return await userCollection.document().setData({
'userName' : userName,
'userPosition' : userPosition,
'userLocation' : userLocation
});
}
如果我可以将如下所示的字段用作Firebase的时间戳,那将是一个很大的帮助.
It would be a great help if I could have a field like below that gets the timestamp for firebase.
'createdOn' : TimestampHere,
推荐答案
您可以使用 FieldValue.serverTimestamp()
serverTimestamp()
:FieldValue返回与set()一起使用的哨兵或update()在写入的数据中包含服务器生成的时间戳.
serverTimestamp()
: FieldValue Returns a sentinel used with set() or update() to include a server-generated timestamp in the written data.
'createdOn':FieldValue.serverTimestamp()
参考文献
- ServerTimestamp
这篇关于如何从Flutter将文档创建的时间戳添加到Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!