Search code examples
flutterdartgoogle-cloud-firestorestream-builder

Compare the condition from the data retrieve from Firestore


I would like to set the condition to verify the userType in the firestore in everytime I login into the app.

For example:

if the userType is Customer I would like go the CustomerMainScreen ;

if the userType is Confinement Lady I would like go the CLLadyMainScreen;

Here is my Firestore image: Firestore

Below is my code:

 Widget build(BuildContext context) {
    return StreamBuilder(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, userSnapshot) {
          // if (userSnapshot.hasData && userSnapshot.data['userType']== 'Confinement Lady') {
          //   return CLLadyMainScreen();
          // }
          // if (userSnapshot.hasData && userSnapshot.data['userType']== 'Customer') {
          //   return CustomerMainScreen();
          // }
          if (userSnapshot.hasData) {
            if (userSnapshot.data()['userType'] == 'Confinement Lady') {
              return CLLadyMainScreen();
            } else if (userSnapshot.data()['userType'] == 'Customer') {
              return CustomerMainScreen();
            }
          }
          return AuthScreen();
        });
  }

But this error pop out when I click the sign in button : Error message

How should I fix this?

The problem exist now: Problem


Solution

  • Firstly you need another Streambuilder to access the documents in Firestore, and pass it another stream to the current user's information. I'm also assuming that every user document in the collection is the user's UID:

    if(userSnapshot.hasData) {
        return StreamBuilder(
          stream: FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser?.uid).snapshots(),
          builder: (context, snapshot) {
          // snapshot returns user doc.
    
            if(snapshot.data == null) {
               return Container(); // Return some kind of spinner or loading widget so firebase can retrieve the data and you don't get an error
            }
    
            if (snapshot.data['userType'] == 'Confinement Lady') {
                  return CLLadyMainScreen();
            } else {
                  return CustomerMainScreen();
            }
        }
    } else {
       return AuthScreen();
    }