Firebase Real Time Database triggers `null` error if there is no matching data

纵然是瞬间 提交于 2021-01-07 02:19:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!