flutter - Flutter Firebase Database, DataSnapshot? how to get values and keys, null safe
问题描述
Using firebase_database: ^7.1.1
Before null safety i used to do like this to get the data from firebase database:
DataSnapshot dataSnapshot = await References.getReferenceYears().once();
Map<dynamic, dynamic> values = dataSnapshot.value;
values.forEach((key, value) {...}
Now when i try do like this, i get the error as bellow:
DataSnapshot? dataSnapshot = await References.getReferenceYears().once();
Map<dynamic, dynamic> values = dataSnapshot.value;
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'List<Object?>' is not a subtype of type 'Map<dynamic, dynamic>'
I think this means that the keys are not being returned in the dataSnapshot.value, how can i use this now to get the (key, value) as before?
If I print the snapshot.value I get like this, so looks like the keys are no longer present in the snapshot.value as before, i don't know where are the keys now:
[{name: 2016-2017}, {name: 2017-2018}, {name: 2018-2019}]
Thanks in advance.
解决方案
Try this
DataSnapshot dataSnapshot = await References.getReferenceYears().once();
(dataSnapshot as Map<dynamic, dynamic>).forEach((key, value) {...}
推荐阅读
- java - JAVA-11: java.net.httpClient 如何设置重试?
- ruby-on-rails - 在 Rails 中构建管理面板
- audio - FFmpeg 检查 7.1 音频的通道是否静音
- javascript - const {tz, msg} = this.state; 语句是什么意思?在下面的代码中是什么意思?
- angular - 动画角度页面
- json - 从引用表中提取数据(以 XML 格式显示)并将其存储在另一个 XML 文件中
- android - Kotlin 扩展 - 合成导入在子类中显示编译错误
- java - Grails 在运行期间出现错误。圣杯 3.0.0
- swift - 无法从通用函数中的 CNMutableContact 中删除项目
- c# - 如何从 datagridview 行列表中删除特定索引