I'm trying to add a check after a user is authenticated if a user has a document in Firestore under a 'users' collection based on their UserID ('uid') via a StreamBuilder.
The issue I have is when I run my code, it works as intended but after a few seconds, it redirects to the 'UserHomeScreen' even if the document does not exist. How can I rectify this so a user without a user document does not get pushed to my 'UserHomeScreen'?
Here is my code:
class UserStream extends StatelessWidget {
const UserStream({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance.collection('users').doc('uid').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return const UserHomeScreen();
} else {
return const SignUpNewUser();
}
},
);
}
}
CodePudding user response:
The snapshot.hasData
is true when the asynchronous call has completed. Even when the document doesn't exist, snapshot.hasData
will still be true once that has been determined.
To ensure the document exists, you'll also want to check:
if (snapshot.hasData && snapshot.data!.exists) {
...
This is also shown in the documentation on handling one time reads.