flutterfirebasedartgoogle-cloud-firestore

Error with redirect function while checking if user is logged in Firebase Flutter


checking some tutorials i try to make a Dart file that helps me to see if the user is still logged on firebase when opening the app and checks if there is a document with his UID to confirm if he finished the registration, here is the code

class Wrapper extends StatelessWidget{

 const Wrapper({super.key});

checkifuserfinishedregistratrion() async {
final FirebaseAuth auth = FirebaseAuth.instance;
final User? user = auth.currentUser;
if (user != null) {
  String uid = user.uid; // <-- User ID

      bool documentCustomerExists =
      await DatabaseMethods().documentDBCustomerExist(uid);
  if (documentCustomerExists) {
    clientExist = true;
  } else {
    clientExist = false;
  }

bool documentStoreExists = await DatabaseMethods().documentDBStoreExist(uid);
  if (documentStoreExists) {
    storeExist = true;
  } else {
    storeExist = false;
  }
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
  body: StreamBuilder(
    stream: FirebaseAuth.instance.authStateChanges(),
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      } else if (snapshot.hasError) {
        return Center(
          child: Text("Error"),
        );
      } else {
        if (snapshot.data == null) {
          return const LogInSession();
        } else {
          checkifuserfinishedregistratrion()
          if (customerExist == true && storeExist == false) {
            return const MainMenuCustomer();
          } else if (customerExist == false && storeExist == true) {
            return const MainMenuStore();
          } else {
            return const RegistrationPage();
          }
        }
      }
    },
  ),
);
   }
   }

The problem that i saw when doing breakpoints is that something happens on the method DatabaseMethods().documentDBStoreExist(uid) because it just skips that part

  Future<bool> documentDBStoreExist(String id) async {
DocumentSnapshot<Map<String, dynamic>> document = await FirebaseFirestore
    .instance
    .collection("StoreData")
    .doc(id)
    .get();

if (document.exists) {
  return true;
} else {
  return false;
}
  }

Also the console sends a very long log that what i read and seems important is:

W/ProviderInstaller( 9421): Failed to report request stats: com.google.android.gms.common.security.ProviderInstallerImpl.reportRequestStats [class android.content.Context, long, long]

E/GoogleApiManager( 9421): Failed to get service from broker.

I am new on Flutter but i have some experience with C# and Visual Studio and from what i see is that maybe i am trying to access the firestore database early and i am missing something to let me the access, is not the rules because i can already create, edit and get the UID.

Any help will be aprreciated


Solution

  • Convert Wrapper class into a statefulWidget and call checkIfUserFinishedRegistration(); within initState() method.

    @override
      void initState() {
        super.initState();
        checkIfUserFinishedRegistration();
      }
    

    Also update checkifuserfinishedregistratrion()

        checkifuserfinishedregistratrion() async {
        final FirebaseAuth auth = FirebaseAuth.instance;
        final User? user = auth.currentUser;
        if (user != null) {
          String uid = user.uid;
        
              bool documentCustomerExists =
              await DatabaseMethods().documentDBCustomerExist(uid);
          if (documentCustomerExists) {
            clientExist = true;
          } else {
            clientExist = false;
          }
        
        bool documentStoreExists = await DatabaseMethods().documentDBStoreExist(uid);
          if (documentStoreExists) {
            storeExist = true;
          } else {
            storeExist = false;
          }
            setState(() {}); //add for rebuild
        }
        }
    

    Update StreamBuilder

    StreamBuilder(
            stream: FirebaseAuth.instance.authStateChanges(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
              } else if (snapshot.hasError) {
                return const Center(child: Text("Error"));
              } else {
                if (snapshot.data == null) {
                  return const LogInSession();
                } else {
                  if (customerExist && !storeExist) {
                    return const MainMenuCustomer();
                  } else if (!customerExist && storeExist) {
                    return const MainMenuStore();
                  } else {
                    return const RegistrationPage();
                  }
                }
              }
            },
          ),