如果没有匹配的数据,Firebase实时数据库将触发"null"错误 [英] Firebase Real Time Database triggers `null` error if there is no matching data
本文介绍了如果没有匹配的数据,Firebase实时数据库将触发"null"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我扑动的代码中,我试图从Firebase实时数据库中获取数据.下面是我的代码.
In my flutter code, I am trying to get data from the Firebase Real-Time Database. Below is my code.
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
的记录,我将收到以下错误
Notice, I am loading data where the email
is equal to abcd@test.com
. The code works great if there are record for abcd@test.com
. But if the database is empty or no records for abcd@test.com
, I AM getting the below error
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
我该如何解决?
推荐答案
问题是存在快照,但是快照中没有数据.最容易抓住这一点:
The problem is that there is a snapshot, but the snapshot contains no data. It's easiest to catch this in:
builder: (context, snapshot) {
if (snapshot == null || !snapshot.hasData || snapshot.data.snapshot.value == null) {
return Container(child: Center(child: Text("No data")));
} else {
...
这篇关于如果没有匹配的数据,Firebase实时数据库将触发"null"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文