firebase - 如果没有匹配的数据,Firebase 实时数据库会触发“null”错误
问题描述
在我的颤振代码中,我试图从 Firebase 实时数据库中获取数据。下面是我的代码。
final DatabaseReference reference = FirebaseDatabase.instance.reference().child('chat_room');
return Scaffold(
body: StreamBuilder(
stream:
reference.orderByChild("email").equalTo("abcd@test.com").onValue,
builder: (context, snapshot) {
if (snapshot == null || !snapshot.hasData) {
return Container(child: Center(child: Text("No data")));
} else {
Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
return ListView.builder(
itemCount: map.values.toList().length,
itemBuilder: (context, index) {
String imageURL = map.values.toList()[index]["imageUrl"];
return Container(
margin: EdgeInsets.only(top: 10),
child: ListTile(
leading: CircleAvatar(
radius: 30.0,
backgroundImage: NetworkImage(imageURL),
backgroundColor: Colors.transparent,
),
title: Text(
map.values.toList()[index]["email"],
),
),
);
});
}
}),
);
请注意,我正在加载email
等于 的数据abcd@test.com
。如果有abcd@test.com
. 但是如果数据库为空或没有记录abcd@test.com
,我会收到以下错误
The following NoSuchMethodError was thrown building StreamBuilder<Event>(dirty, state: _StreamBuilderBaseState<Event, AsyncSnapshot<Event>>#ad47f):
The getter 'values' was called on null.
Receiver: null
Tried calling: values
The relevant error-causing widget was
StreamBuilder<Event>
package:xxx/…/chat/chat_list_supplier.dart:19
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _ChatListSupplierState.build.<anonymous closure>
package:xxx/…/chat/chat_list_supplier.dart:28
我怎样才能解决这个问题?
解决方案
问题是有快照,但快照不包含数据。最容易抓住这一点:
builder: (context, snapshot) {
if (snapshot == null || !snapshot.hasData || snapshot.data.snapshot.value == null) {
return Container(child: Center(child: Text("No data")));
} else {
...
推荐阅读
- node.js - 如何在节点 ejs 中显示来自动态路径的图像
- java - 持久的 Google 登录 Android Studio
- python - 如何检测不和谐的用户流活动更新(discord.py)
- javascript - 在所有文件中全局导入 ReactJS 组件
- python - 必须是实数,而不是列表
- javascript - 直接滚动一个div
- python - 如何在 python kivy 中删除小部件
- angular - 使用本地存储在 Angular 中保存数据
- python - 按列将单个列表写入 csv
- vue.js - 使用名称中包含“-”的图标的vue离子问题示例“arrow-back”