我在用户相互传递的消息中创建相同的时间戳时遇到问题。
这是发送消息的功能:
void onSendMessage(String content, int type) {
if (content.trim() != '') {
textEditingController.clear();
var documentReference = Firestore.instance
.collection('messages')
.document(groupChatId)
.collection(groupChatId)
.document(DateTime.now().millisecondsSinceEpoch.toString());
Firestore.instance.runTransaction((transaction) async {
await transaction.set(
documentReference,
{
'idFrom': id,
'idTo': peerId,
'timestamp': DateTime.now().millisecondsSinceEpoch.toString(),
'content': content,
'type': type
},
);
});
cacheSet(groupChatId, content, peerNickname, peerAvatar);
listScrollController.animateTo(0.0,
duration: Duration(milliseconds: 300), curve: Curves.easeOut);
} else {
Fluttertoast.showToast(msg: 'Nothing to send');
}
}
但是,此
DateTime.now().millisecondsSinceEpoch.toString()
根据用户的设备创建时间戳。这意味着如果用户A在10:00时向用户B发送一条消息(“hello”),但是如果用户B答复(“世界”)并且其设备时间为9:50,则它将在用户A的消息为假之前显示。像这样:
09:50 userB - "world"
10:00 userA - "hello"
与设备时间无关,是否有通用的时间格式?是否可以在不使用外部API的情况下进行设置?
最佳答案
在将代码更改为 FieldValue.serverTimestamp()之前,我遇到了这个问题。
Change DateTime.now().millisecondsSinceEpoch.toString() to FieldValue.serverTimestamp().
所以试试这个:
{
'idFrom': id,
'idTo': peerId,
'timestamp': FieldValue.serverTimestamp(),
'content': content,
'type': type
},
检查那些:FieldValue Firebase,Flutter: Firebase FieldValue.serverTimestamp()。
希望这有所帮助!
关于flutter - Flutter聊天应用程序可保存设备时间中的消息时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60357312/