Reputation: 432
Here, I'm trying to print the username of the user and it produces the following error.
I created a function userData() and the code is
userData() async
{
var userData = await _db.collection('users').document(_uuid).get();
return userData;
}
Where I'll just get the data of the specific user using uid and returning it.
The code I used to print the data is as follow
return FutureBuilder(
future: authService.userData(),
builder: (_,snapshots){
if(snapshots.connectionState == ConnectionState.waiting)
{
return Center(child: Text('Loading...'),);
}
else{
print("Snapshots: "+snapshots.toString());
return ListView.builder(itemCount: 1, itemBuilder: (_,index){
return ListTile(
title: Text(snapshots.data["username"].toString()),
);
});
}
}
);
The structure of firestore is
Collection('user') -> document(uid) -> 1.username 2.email ....
What is the reason for this error and how to resolve it?
Upvotes: 0
Views: 348
Reputation: 317760
The error message is telling you that snapshots.data
is null, so you can't index into it with the []
operator.
Before using a DocumentSnapshot, you should check to see if it exists before accessing its field data. The snapshot's data property will be null if the document doesn't exist.
Upvotes: 2
Reputation: 352
For Firestore I would recommend using Stream Builder rather than future Builder.
return StreamBuilder(
stream: Firestore.instance
.collection('user')
.document(uid)
.snapshots(),
builder: (_,snapshot){
if(!snapshot.hasData)
{
return Center(child: Text('Loading...'),);
}
else{
return ListView.builder(itemCount: 1, itemBuilder: (_,index){
return ListTile(
title: Text(snapshots.data["username"].toString()),
);
});
}
}
);
Upvotes: 0