首页 > 解决方案 > 用户第一次登录flutter firestore时如何处理空值

问题描述

您好我正在构建一个应用程序,用户将在其中添加某些项目,这些项目将显示在网格视图中。但是当他们注册时,在那个阶段他们还没有在数据库中添加任何东西,所以 firestore 返回空值。

这是一个新用户,因此 firestore 中没有当前用户的数据

我正在使用以下方法检查空值:

builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
  if (!snapshot.hasData || !snapshot.data!.exists) {}

但是我仍然收到以下错误,因为它没有处理这种情况:

The following NoSuchMethodError was thrown building 
StreamBuilder<DocumentSnapshot<Object?>>(dirty,
state: _StreamBuilderBaseState<DocumentSnapshot<Object?>,
AsyncSnapshot<DocumentSnapshot<Object?>>>#3898f):
The method '/' was called on null.
Receiver: null
Tried calling: /(60)

The relevant error-causing widget was:

StreamBuilder<DocumentSnapshot<Object?>>

标签: fluttergoogle-cloud-firestore

解决方案


将此作为社区 Wiki 发布,因为它基于 @esentis 评论。

您必须使用以下代码检查快照中的数据是否为空:

if (!snapshot.hasData){
    return Center(child: CircularProgressIndicator());
}

推荐阅读