首页 > 解决方案 > StreamBuilder 快照是否为空

问题描述

StreamBuilder(
        stream: firestore
            .collection('Product')
            .doc(order.productId)
            .collection('AbleToReview')
            .doc(auth.currentUser.uid)
            .snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Text('Something went wrong');
          }

          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          if (snapshot.data==null){
            return Text('no data');
          } else {
            return Text('have data');
          }
        }
    )

有时firestore.collection('Product').doc(order.productId).collection('AbleToReview').doc(auth.currentUser.uid).snapshots()查询中不存在数据。由于取决于数据是否存在,我尝试重新使用不同的小部件。但snapshot.data==null!snapshot.hasData不是我想要的正确方式。

标签: fluttergoogle-cloud-firestoreflutter-layout

解决方案


您可以使用来检查查询中的实际数据是否为空snapshot.data.documents.isEmpty()

您可以将代码更新为以下代码:

    if (snapshot.data==null || snapshot.data.data().isEmpty()){
        return Text('no data');
    } else {
        return Text('have data');
    }

推荐阅读