聊天消息排序不正确

Chat messages not ordering correctly

我正在使用 Firestore 和 Flutter 作为聊天应用。它工作正常,但我看到了这个问题。有时消息不按顺序显示。例如,通常它们被排序为最近的在底部。但我在 iOS 和 Android 模拟器上进行测试,发现有时消息没有按顺序显示。例如,我在 iOS 上发送消息,一切正常(按顺序)。然后我发送不同的模拟器(例如 Android),消息显示在顶部,然后开始下降(在 iOS 上发送的消息之上)。

这是我的代码:

            child: new FirestoreAnimatedList(
              query: reference
                  .orderBy('timestamp', descending: true)
                  .snapshots(),
              padding: new EdgeInsets.all(8.0),
              reverse: true,
              itemBuilder: (_, DocumentSnapshot snapshot,
                  Animation<double> animation, int x) {
                return new Chat(
                    snapshot: snapshot, animation: animation);
              },
            ),

'timestamp': DateTime.now(),

我试过这个但是同样的问题:

'timestamp': DateTime.now().millisecondsSinceEpoch.toString()

我找了几个星期的答案,但没有找到。有人可以帮忙吗?

您可能会遇到此问题,因为设备报告的时间不同。

要解决这个问题,请使用服务器时间而不是本地时间。这是通过将 timestamp 字段设置为 FieldValue.serverTimestamp().

来完成的

Documentation.