如何解决使用 StreamBuilder 时如何将 serverTimestamp 转换为 String
我想要的
根据服务器时间戳对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(),
预期行为
列表视图根据服务器时间戳顺序显示
我得到了什么
这个错误:
期望类型为“String”的值,但得到类型为“Timestamp”的值
我的尝试
我尝试在将数据发送到 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,),);
},);
解决方法
你可以试试这个:
Firestore.instance
.collection("things")
.orderBy('createdAt',descending: true or false).getDocuments()
然后您可以使用 Timestamp 在客户端存储 createdAt,您可以使用 Timestamp.now() 获取当前时间戳
,由于预期行为是根据服务器时间戳对 ListView
项进行排序,因此您可以在从 Firestore
获取列表后对其进行排序。
final things = snapshot.data.docs;
things.sort((a,b) {
return (a['timestamp'] as Timestamp).compareTo(b['timestamp'] as Timestamp);
});
,
问题与我最初的想法完全不同。
老实说,我忘记了当我从 Firestore 检索数据进行处理时,我将 Map
设置为 Map<String,String>
,以前没问题,因为我只有 String,但现在有了 Timestamp输入,它不起作用。
问题的答案只是将 Map<String,String>
更改为 Map<String,dynamic>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。