首页 > 解决方案 > 如果没有匹配的数据,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

我怎样才能解决这个问题?

标签: firebaseflutterfirebase-realtime-database

解决方案


问题是有快照,但快照不包含数据。最容易抓住这一点:

  builder: (context, snapshot) {
    if (snapshot == null || !snapshot.hasData || snapshot.data.snapshot.value == null) {
      return Container(child: Center(child: Text("No data")));
    } else {
      ...

推荐阅读