问题
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"],
),
),
);
});
}
}),
);
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
How can I fix this?
回答1:
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 {
...
来源:https://stackoverflow.com/questions/64876013/firebase-real-time-database-triggers-null-error-if-there-is-no-matching-data