flutter - Flutter聊天应用程序可保存设备时间中的消息时间戳

标签 flutter dart timestamp

我在用户相互传递的消息中创建相同的时间戳时遇到问题。

这是发送消息的功能:

  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 FirebaseFlutter: Firebase FieldValue.serverTimestamp()

希望这有所帮助!

关于flutter - Flutter聊天应用程序可保存设备时间中的消息时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60357312/

相关文章:

flutter - 互联网连接困惑

Flutter 在选择时更改 NavigationBarThemeData labelTextStyle 颜色

gcc - 汇编指令 : rdtsc

java - 使用仅字符串格式化程序将纪元时间戳字符串转换为Joda日期时间

python - pandas - 多索引切片未按预期调整索引值

flutter - flutter -在日历插件中创建动态标记事件

firebase - 如何在 Flutter 中连接两个 Firestore 集合中的数据?

dart - polymer Dart 与 polymer js : does it matter when using the component?

regex - 如何将所有正则表达式匹配项放入字符串列表中

flutter - Android资源链接失败Flutter