在 Flutter 中处理 Firebase Stream 对象
我正在尝试从 Flutter 中的 Firebase 实时数据库接收数据。我无法让它工作 - 到目前为止我找到的所有解决方案都不起作用。
与数据库的连接正在工作并正在获取数据:
String userid = FirebaseAuth.instance.currentUser!.uid;
DatabaseReference _database =FirebaseDatabase.instance.ref();
void _getData(){
_itemStream = _database.child('users/$userid/items/').onValue.listen((event) {
final Object? mydata = event.snapshot.value;
print(mydata.toString());
});
}
这为我提供了一组作为对象的数据。 Print-Statement 返回这个,这是节点的正确数据集:
{1646396962722: {mhd: 2022-03-04 12:29:22.722218, name: Hund, startdate: 2022-03-04 12:29:22.722106, fach: 0}, 1646396401456: {mhd: 2022-03-04 12:20:01.461668, name: Hund, startdate: 2022-03-04 12:20:01.456343, fach: 0}, 1646396946311: {mhd: 2022-03-04 12:29:06.312466, name: Maus, startdate: 2022-03-04 12:29:06.311793, fach: 0}}
我无法解决的问题是:如何循环此数据集并将其放入 Dart 中的列表中。如果我尝试类似的操作
mydata?.forEach()
,则会出现错误:
没有为类型“Object”定义方法“forEach”。
我真的被困住了。也许任何人都可以给我一个如何解决这个问题的提示。
谢谢!
I'm trying to receive Data from the Firebase Realtime Database in Flutter. I can't get it working - all the solutions I found so far don't work.
The connection to the database is working and getting Data:
String userid = FirebaseAuth.instance.currentUser!.uid;
DatabaseReference _database =FirebaseDatabase.instance.ref();
void _getData(){
_itemStream = _database.child('users/$userid/items/').onValue.listen((event) {
final Object? mydata = event.snapshot.value;
print(mydata.toString());
});
}
This gives me my set of Data as an Object. The Print-Statement returns this, which is the correct Dataset for the node:
{1646396962722: {mhd: 2022-03-04 12:29:22.722218, name: Hund, startdate: 2022-03-04 12:29:22.722106, fach: 0}, 1646396401456: {mhd: 2022-03-04 12:20:01.461668, name: Hund, startdate: 2022-03-04 12:20:01.456343, fach: 0}, 1646396946311: {mhd: 2022-03-04 12:29:06.312466, name: Maus, startdate: 2022-03-04 12:29:06.311793, fach: 0}}
The problem I can't solve is: How to Loop through this Dataset and get it into a List in Dart. If I try something like
mydata?.forEach()
I get the Error:
The method 'forEach' isn't defined for the type 'Object'.
Im really stuck. Maybe anyone can give me a tip how to approach this.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您查看数据集,这实际上是一个
Map
。您需要将其转换为更好的 Dart 对象或使用for in
循环。请参见下面的示例:If you look at your dataset, this is in fact a
Map<dynamic, dynamic>
. You need to convert this to a better Dart object or use thefor in
loop. see the example below:只有草图代码:
only sketchup code: