Firebase 如何在使用StreamBuilder时将serverTimestamp转换为字符串
我想要什么 根据服务器时间戳订购ListView的步骤Firebase 如何在使用StreamBuilder时将serverTimestamp转换为字符串,firebase,flutter,dart,google-cloud-firestore,flutter-streambuilder,Firebase,Flutter,Dart,Google Cloud Firestore,Flutter Streambuilder,我想要什么 根据服务器时间戳订购ListView的步骤 return StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection('things').orderBy('timestamp').snapshots(), 我的代码 return StreamBuilder<QuerySnapshot>( stream: _firestore.collection('thing
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('things').orderBy('timestamp').snapshots(),
我的代码
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集合:
onPressed: () {
FirebaseFirestore.instance.collection('things').add(
{
// some code
'timestamp': FieldValue.serverTimestamp(),
},
);
从firestore获取数据并根据服务器时间戳对其进行排序
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('things').orderBy('timestamp').snapshots(),
但它会显示以下错误,并且不会编译
没有为类型“String”定义方法“snapshots”
官方文件也没有说要把它们转换成字符串
如果有人知道如何解决这个问题,请帮帮我,我真的被困在这里了
完整的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,
),
);
},
);
返回StreamBuilder(
流:_firestore.collection('things').orderBy('timestamp').snapshots(),
生成器:(上下文,快照){
列表putDataHere=[];
最终结果=snapshot.data.docs;
for(事物中的事物){
final myData=Map.from(thing.data());
最终神话=myData['dataTitle'];
final thingWidget=文本(虚构);
添加(thingWidget);
}
扩大回报(
子:ListView(
孩子们:在这里,
),
);
},
);
您可以尝试以下方法:
Firestore.instance
.collection("things")
.orderBy('createdAt', descending: true or false).getDocuments()
然后,您可以使用Timestamp在客户端存储createdAt,并使用Timestamp获取当前时间戳。现在()由于预期的行为是根据服务器时间戳对
ListView
项进行排序,您可以在从Firestore
获取列表后对其进行排序
final things=snapshot.data.docs;
事物。排序((a,b){
返回(a['timestamp']作为时间戳)。比较(b['timestamp']作为时间戳);
});
这个问题与我最初的想法完全不同
我真的忘记了,当我从Firestore检索数据来处理它时,我将我的Map
设置为Map
,以前还可以,因为我只有字符串,但现在我有了时间戳类型,它就不起作用了
这个问题的答案就是简单地将
Map
更改为Map
您想要实现的是按时间顺序对所有元素进行排序,对吗?您可以发布您的列表视图
代码吗?@VictorEronmosele我编辑了我的问题,以包含列表视图我没有使用您的代码,但这给了我一个提示,原来问题不在于它从firebase获取数据的方式,orderBy
可以使用Timestamp
很好。问题就在我的地图上。我完全忘记了,但我将它设置为Map
。现在我还有Timestamp
类型,它抱怨无法转换。所以我把地图改成了Map
,它解决了这个问题。