【问题标题】:How to convert serverTimestamp to String when using StreamBuilder使用 StreamBuilder 时如何将 serverTimestamp 转换为 String
【发布时间】:2021-08-26 14:12:09
【问题描述】:

我想要什么

根据服务器时间戳排序 ListView

我的代码

添加到 Firestore 集合:

onPressed: () {
FirebaseFirestore.instance.collection('things').add(
  {
    // some code
    'timestamp': FieldValue.serverTimestamp(),
  },
);

从 firestore 获取数据并根据服务器时间戳对其进行排序

return StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance.collection('things').orderBy('timestamp').snapshots(),

预期行为

列表视图根据服务器时间戳排序显示

我得到了什么

这个错误:

需要一个“字符串”类型的值,但得到一个“时间戳”类型的值

我的尝试

我尝试在将数据发送到 Firestore 时添加toString()'timestamp': FieldValue.serverTimestamp().toString(),但后来 Firestore 上的数据没有存储时间戳,而是存储了 FieldValue(Instance of 'FieldValueWeb')

我知道当我从 firestore 获取数据时,我可能必须将它们转换为 String,但我不知道该怎么做。我尝试在将数据输入流时添加toString()

stream: FirebaseFirestore.instance.collection('things').orderBy('timestamp').toString().snapshots()

但随后它显示以下错误并且不会编译。

没有为“String”类型定义方法“snapshots”。

官方文档也没有说要转成String。

如果有人知道如何解决这个问题,请帮助我,我真的被困在这里了。


完整的 StreamBuilder 和 ListView 代码

return StreamBuilder<QuerySnapshot>(
  stream: _firestore.collection('things').orderBy('timestamp').snapshots(),
  builder: (context, snapshot) {
    List<Text> putDataHere = [];

    final things = snapshot.data.docs;
    for (var thing in things) {
      final myData = Map<String, String>.from(thing.data());
      final myThing = myData['dataTitle'];
      final thingWidget = Text(myThing);
      putDataHere.add(thingWidget);
    }
    return Expanded(
      child: ListView(
        children: putDataHere,
      ),
    );
  },
);

【问题讨论】:

  • 你想要实现的是将所有元素按时间顺序排列对吧?
  • 您可以发布您的ListView 代码吗?
  • @VictorEronmosele 我编辑了我的问题以包含 ListView

标签: firebase flutter dart google-cloud-firestore flutter-streambuilder


【解决方案1】:

你可以试试这个:

Firestore.instance
     .collection("things")
     .orderBy('createdAt', descending: true or false).getDocuments()

然后您可以使用 Timestamp 在客户端存储 createdAt,您可以使用 Timestamp.now() 获取当前时间戳

【讨论】:

    【解决方案2】:

    由于预期的行为是 ListView 项目是根据服务器时间戳排序的,因此您可以在从 Firestore 获取列表后对列表进行排序。

        final things = snapshot.data.docs;
        things.sort((a, b) {
            return (a['timestamp'] as Timestamp).compareTo(b['timestamp'] as Timestamp);
        });
    
    

    【讨论】:

    • 我没有使用您的代码,但这给了我一个提示,事实证明问题不在于它从 firebase 获取数据的方式,orderBy 可以采用 Timestamp 就好了。问题出在我的地图上。我完全忘记了它,但我将它设置为Map&lt;String, String&gt;。现在我也有Timestamp 类型,它抱怨它无法转换。所以我只是将地图更改为Map&lt;String, dynamic&gt;,它解决了问题。
    【解决方案3】:

    问题与我最初的想法完全不同。

    老实说,当我从 Firestore 检索数据进行处理时,我将 Map 设置为 Map&lt;String, String&gt;,以前没问题,因为我只有 String,但现在我有 Timestamp 类型,它没有不行。

    问题的答案只是简单地将Map&lt;String, String&gt; 更改为Map&lt;String, dynamic&gt;

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 2021-07-26
      • 2011-08-24
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2011-06-27
      • 2019-02-16
      • 2023-03-31
      相关资源
      最近更新 更多