Firebase 실시간 데이터베이스는 일치하는 데이터가없는 경우 'null'오류를 트리거합니다.

Nov 17 2020

내 flutter 코드에서 Firebase 실시간 데이터베이스에서 데이터를 가져 오려고합니다. 아래는 내 코드입니다.

final DatabaseReference reference = FirebaseDatabase.instance.reference().child('chat_room');

    return Scaffold(
      body: StreamBuilder(
          stream:
              reference.orderByChild("email").equalTo("[email protected]").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가) 인 데이터를로드 하고 [email protected]있습니다. 에 대한 레코드가 있으면 코드가 잘 작동합니다 [email protected]. 그러나 데이터베이스가 비어 있거나에 대한 레코드가 없으면 [email protected]아래 오류가 발생합니다.

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

이 문제를 어떻게 해결할 수 있습니까?

답변

1 FrankvanPuffelen Nov 17 2020 at 14:36

문제가 있다는 것입니다 이다 스냅 샷되지만 스냅 샷 데이터가없는. 이것을 잡는 것이 가장 쉽습니다.

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