简体   繁体   中英

Flutter How to check whether the user sign up with google provider before?

I want to check whether the user has signed up before or not (if this is his first time I will send him to write some data if not he will enter to the main page of the app).

GoogleSignInAccount _user;
GoogleSignInAccount get user => _user;

Future googlelogin() async {
  try {
  final googleUser = await googleSignIn.signIn();
  if (googleUser == null) return;
  _user = googleUser;

  final googleAuth = await googleUser.authentication;

  final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );

  await FirebaseAuth.instance.signInWithCredential(credential);
} catch (e) {
  print(e.toString());
}
notifyListeners();

}

I also have a StreamBuilder to check the data that user enter

StreamBuilder<Object>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: CircularProgressIndicator.adaptive(),
          );
        } else if (snapshot.hasData) {
          return LoggedInWidget();
        } else if (snapshot.hasError) {
          return Center(
            child: Text('Something went wrong'),
          );
        } else {
          return SignUp();
        }
      })

You can use the pre-built method "isNewUser" of the "UserCredential" class. Call the sing in with credentials function from a variable and use said variable to perform the check.

...
var result =
        await FirebaseAuth.instance.signInWithCredential(credential);

   if (result.additionalUserInfo!.isNewUser) {

// Perform what you need to do for new users here
// like creating a user document

      }else {

         //Perform what you want to do for old users here
         //like fetching a specific user document

}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM