How to handle null value when user logins first time in flutter firestore

Viewed 156

Hi I am building a app where user will add certain items and these items will be shown in a gridview. But when they register, at that stage they are yet to add anything in the database so firestore return nulls.

This is a new user so there is no data for the current user in firestore

I am checking for null value using:

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

But still i am getting following error because it is not handling this scenario:

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?>>

1 Answers

Posting this as a Community Wiki as it's based on @esentis comment.

You have to check if the data in the snapshot is null with the following code:

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