如何在 flutter 中使用 where 和 orderby 来使用 firestore?

How can use firestore using where and orderby in flutter?

如何在 flutter 中使用 where 和 orderby 来使用 firestore?

当我想同时使用两者时,出现错误。

Exception has occurred.
_CastError (Null check operator used on a null value)

代码

StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('Posts')
            .where('country', isEqualTo: user.country)
            //.where('country', isEqualTo: 'Australia')
            .orderBy('time', descending: true)
            .snapshots(),
        builder: (context,
            AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          //print(user.country);
          return ListView.builder(
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (context, index) => Container(
              margin: EdgeInsets.symmetric(
                  horizontal: width > webScreenSize ? width * 0.3 : 0,
                  vertical: width > webScreenSize ? 15 : 0),
              child: PostCard(
                snap: snapshot.data!.docs[index],
              ),
            ),
          );
        },

那么,为什么我收不到数据呢?我得到了 user.value.

问题是你告诉 Flutter snapshot.data 肯定有一个值,而实际上它不在这里:

return ListView.builder(
  itemCount: snapshot.data!.docs.length,

我建议再次阅读 StreamBuilder 的文档,因为您需要处理的状态比 snapshot.connectionState == ConnectionState.waiting 多得多。

例如,可能有错误,或者由于其他原因没有数据:

StreamBuilder(
  stream: FirebaseFirestore.instance
      .collection('Posts')
      .where('country', isEqualTo: user.country)
      .orderBy('time', descending: true)
      .snapshots(),
  builder: (context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    //  Handle error
    if (snapshot.hasError) {
      return const Center(
        child: Text(snapshot.error),
      );
    }

    //  Handle lack of data
    if (!snapshot.hasData) {
      return const Center(
        child: Text("Something when wrong - no data available"),
      );
    }

    return ListView.builder(
      itemCount: snapshot.data!.docs.length,
      itemBuilder: (context, index) => Container(
        margin: EdgeInsets.symmetric(
            horizontal: width > webScreenSize ? width * 0.3 : 0,
            vertical: width > webScreenSize ? 15 : 0),
        child: PostCard(
          snap: snapshot.data!.docs[index],
        ),
      ),
    );