如何从Flutter将文档创建的时间戳添加到Firestore [英] How to add timestamp on document create to Firestore from Flutter

查看:64
本文介绍了如何从Flutter将文档创建的时间戳添加到Firestore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写代码,以将数据设置为从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆