在Flutter中使用Firebase身份验证检查用户是否是新用户

时间:2018-08-13 09:53:43

标签: firebase authentication dart flutter

根据this page的底部,AdditionalUserInfo提供了一种称为isNewUser()的方法,用于检查例如社交登录名(Facebook,Google等)是登录还是注册。 this answer.中给出了一个示例Flutter的问题是我找不到任何名为AdditionalUserInfo的类或名为getAdditionalUserInfo()的函数。所以没有人知道如何检查用户是否首次注册,最好是使用Facebook和Firebase身份验证。

我正在使用firebase_authflutter_facebook_login

4 个答案:

答案 0 :(得分:2)

我不认为这是在软件包的当前版本中实现的。我前段时间也需要类似的东西。我要做的是从我的云函数中向用户文档添加isNew:true的标志,并在应用程序中通过某些操作(例如教程阶段)后为每个用户更改它。

答案 1 :(得分:2)

AdditionalUserInfo是AuthResult类的方法。如果要检查用户是否是首次登录,则可以使用additionalUserInfo.isNewUser的值。以下代码使用Google Auth登录用户。

Future<FirebaseUser> _signIn() async {
 try {
  GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
  GoogleSignInAuthentication gSA = await googleSignInAccount.authentication;
  final AuthCredential credential = GoogleAuthProvider.getCredential(
    accessToken: gSA.accessToken,
    idToken: gSA.idToken,
  );
  AuthResult authResult = await _auth.signInWithCredential(credential);
  if (authResult.additionalUserInfo.isNewUser) {
    //User logging in for the first time
    // Redirect user to tutorial 
  }
  else {
    //User has already logged in before.
    //Show user profile
  }
} catch (e) {
  print(e.message);
}}

编辑:由于该问题是针对Facebook登录的,所以我还要添加该代码。下面的代码使用flutter_facebook_loginfirebase_auth包。

Future<FirebaseUser> _facebookAuthHandler() async {
  final result = await facebookLogin.logInWithReadPermissions(['email']);
  final AuthCredential credential = FacebookAuthProvider.getCredential(accessToken: result.accessToken.token);
  AuthResult authResult = await _auth.signInWithCredential(credential);
  if (authResult.additionalUserInfo.isNewUser) {
    //TODO User logging in for the first time. Redirect to Pages.SignUp Page
  }
  else {
    //TODO User has already logged in before. Redirect to Home Page
  }

}

答案 2 :(得分:1)

在最近的版本中,没有 authResult 类,而是有 userCredential 类。这将为您提供有关该用户的其他信息,以便您知道该用户是否被认识。

Future<void> signInWithGoogle() async {
GoogleSignInAccount account = await googleSignIn.signIn();
GoogleSignInAuthentication authentication = await account.authentication;
OAuthCredential credential = GoogleAuthProvider.credential(
  accessToken: authentication.accessToken,
  idToken: authentication.idToken,
);
UserCredential userCredential =
    await _firebaseAuth.signInWithCredential(credential);
User user = userCredential.user;
if (userCredential.additionalUserInfo.isNewUser) {
  //Here, you can do something with the profile of a new user. eg. upload information  
  //in database
}

}

答案 3 :(得分:0)

或者只是做类似的事情:

final userCredential = await _firebaseAuth.signInWithPopup(provider);
final username = userCredential.additionalUserInfo?.username;