在 firebase flutter 中使用 .where('uid', isEqualTo: uid) 时出现空错误

getting null error when using .where('uid', isEqualTo: uid) in firebase flutter

我们正在制作像 Instagram 这样的主页,我现在只想显示用户 post。 代码是这样的

 StreamBuilder(
    stream: FirebaseFirestore.instance.collection('posts').orderBy("datePublished", descending: true).snapshots(),
    builder: (context,
        AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
         return const Center(
             child: CircularProgressIndicator(),
         );
      }
    return PageView.builder(/*the rest of the code ...*/);

它起作用了,但它显示了所有 post 所以我添加了这个

.where('uid', isEqualTo: uid)

看起来像这样 内部小部件构建

var uid = FirebaseAuth.instance.currentUser!.uid;

体内像这样

StreamBuilder(
    stream: FirebaseFirestore.instance.collection('posts').where('uid', isEqualTo: uid).orderBy("datePublished", descending: true).snapshots(),
    builder: (context,
        AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
         return const Center(
             child: CircularProgressIndicator(),
         );
      }
    return PageView.builder( //to make the page scroll
      itemCount: snapshot.data!.docs.length,/*the rest of the code*/);

它在第

行显示错误

itemCount: snapshot.data!.docs.length, saying Null check operator used on a null value

数据库看起来像这样

错误提示snapshot.datanull。当 snapshot.connectionState 等于 ConnectionState.none 时,当流被初始化并且应该受到保护时,可能会发生这种情况。

根据 PageView 的设置方式,您可以通过将该行更改为 itemCount: snapshot.data?.docs.length ?? 0,snapshot.data 为空时将传递 0。

另一种方法是事先检查空值。

if (snapshot.data == null) {
    return SomeWidget():
} else {
    return PageView.builder( //to make the page scroll
      itemCount: snapshot.data!.docs.length,/*the rest of the code*/
    );
}