StreamBuilder 总是在 print(snapshot.hasData) 中返回 false

StreamBuilder always returning false in print(snapshot.hasData) in flutter

我将在 flutter 中显示来自 firebase firestore 的消息,但是当我在快照中设置条件时总是返回 false 这是我的代码

服务

Stream<List<MessageModel>> getMessagesByUserid({int userId}) {
    try {
      return firestore
          .collection('messages')
          .where('userId', isEqualTo: userId)
          .snapshots()
          .map((QuerySnapshot list) {
        var result = list.docs.map<MessageModel>((DocumentSnapshot message) {
          print('from service : ' + message.data().toString());
          return MessageModel.fromJson(message.data());
        }).toList();

        result.sort(
          (MessageModel a, MessageModel b) =>
              a.createdAt.compareTo(b.createdAt),
        );
        return result;
      });
    } catch (e) {
      throw Exception(e);
    }
  }

并用这个

打电话
 Widget content() {
      return StreamBuilder<List<MessageModel>>(
          stream: MessageService()
              .getMessagesByUserid(userId: authprovider.user.id),
          builder: (context, snapshot) {
            print(snapshot.hasData);
            if (snapshot.hasData) {
              return ListView(
                padding: EdgeInsets.symmetric(
                  horizontal: defaultMargin,
                ),
                children: snapshot.data
                    .map(
                      (MessageModel message) => ChatBubble(
                        isSender: message.isFromUser,
                        text: message.message,
                        product: message.product,
                      ),
                    )
                    .toList(),
              );
            } else {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
          });
    }

当我在服务中打印时,我得到

I/flutter (29881): from service : {createdAt: 2021-06-28 16:29:25.106709, product: {}, userImage: https://ui-avatars.com/api/?name=eka&color=7F9CF5&background=EBF4FF, isFromUser: true, message: tanpa, userName: eka, userId: 2, updatedAt: 2021-06-28 16:29:25.106811}

但是当我打印(snapshot.hasData)时总是返回 false

I/flutter (29881): false

如果您在使用 StreamBuilder 时需要更多粒度,请测试 snapshot.connectionState 而不是 snapshot.hasData

如果 Stream 返回 null

snapshot.hasData 仍然可以为 false