代码之家  ›  专栏  ›  技术社区  ›  harunB10

颤振聊天应用程序保存了一个设备的消息时间戳

  •  0
  • harunB10  · 技术社区  · 5 年前

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

    此函数用于发送消息:

      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() 基于用户的设备创建时间戳。这意味着如果userA在10:00向userB发送一条消息(“hello”),但是如果userB回复(“world”),并且他的设备时间是9:50,它将显示在userA的消息之前,这是假的。

    像这样:

    09:50 userB - "world"
    10:00 userA - "hello"
    

    是否有一个通用的时间格式而不考虑设备时间?是否可以不使用外部API进行设置?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Abdelbaki Boukerche    5 年前

    在我把代码改成 .

    改变 日期时间.now()米lisecondssinceepoch.toString() FieldValue.serverTimestamp() .

    所以试试这个:

     {
            'idFrom': id,
            'idTo': peerId,
            'timestamp': FieldValue.serverTimestamp(),
            'content': content,
            'type': type
      },
    

    检查这些: FieldValue Firebase , Flutter: Firebase FieldValue.serverTimestamp() .

    希望这有帮助!!