Home > Software engineering >  Flutter Firestore check if user exists via StreamBuilder:
Flutter Firestore check if user exists via StreamBuilder:

Time:11-24

I'm trying to add a check in my app via a StreamBuilder to show users different screens based upon if a user's document exists in Firestore. My code technically works but on hot reload, it shows my 'AddUser' screen for a couple of seconds before moving over to my 'UserHomeScreen'. I was wondering how to rectify this so the 'AddUser' screen does not show my 'AddUser' screen at all if the user document exists.

Here is my code:

class UserStream extends StatelessWidget {
  const UserStream({Key? key}) : super(key: key);
  

  @override
  Widget build(BuildContext context) {
    FirebaseAuth auth = FirebaseAuth.instance;
     String uid = auth.currentUser!.uid.toString();
    return StreamBuilder<dynamic>(
      stream: FirebaseFirestore.instance.collection('users').doc(uid).snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasData && snapshot.data!.exists) {
          return const UserHomeScreen();
        } else {
          return AddUser(youtubeLink: '', bio: '', bioLink: '', displayName: '', instaLink: '', profilePhoto: '', tiktokLink: '', username: '',);
        }
      },
    );
  }
}

CodePudding user response:

You could structure your builder like this:

builder: (context, snapshot) {
  if (snapshot.hasData) {
    if (snapshot.data!.exists){
      return const UserHomeScreen();
    } else {
      return AddUser(youtubeLink: '', bio: '', bioLink: '', displayName: '', instaLink: '', profilePhoto: '', tiktokLink: '', username: '',);
    }
  } else {
    return CircularProgressIndicator();
  }
},

This way, you show a CircularProgressIndicator while the snapshot is resolving. At this point, you don't know of your data exists or not.

As soon as the snapshot is resolved and you have information, whether your data exists, you can show the respective screen.

  • Related