gpt4 book ai didi

android - 如何在flutter中使用firebase登录谷歌时检查用户是新用户还是现有用户?

转载 作者:行者123 更新时间:2023-12-04 11:26:25 30 4
gpt4 key购买 nike

我正在开发一个项目,其中用户数据将保存在 Fire 存储中,当用户使用谷歌登录时,我正在为用户制作新文档。这是我下面的代码

import 'package:firebase_auth/firebase_auth.dart';
import 'package:gfd_official/User/User.dart';
import 'package:gfd_official/services/database.dart';
import 'package:google_sign_in/google_sign_in.dart';

class GSignInhelp {
final FirebaseAuth _auth = FirebaseAuth.instance;

//Firebase User
Userdat _userFromFirebase(User user) {
return user != null ? Userdat(uid: user.uid) : null;
}

//auth change user stream
Stream<Userdat> get user {
return _auth.authStateChanges().map(_userFromFirebase);
}

Future signInWithGoogle() async {
GoogleSignIn googleSignIn = GoogleSignIn();
final account = await googleSignIn.signIn();
final auth = await account.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: auth.accessToken,
idToken: auth.idToken,
);
try {
final res = await _auth.signInWithCredential(credential);
User user = res.user;
await DatabaseService(uid: user.uid)
.updateUserRole(user.displayName, user.email, 'basic');
return _userFromFirebase(user);
} catch (e) {
print(e.toString());
return null;
}
}

Future logOut() async {
try {
GoogleSignIn().signOut();
return await _auth.signOut();
} catch (e) {
print(e.toString());
return null;
}
}
}
我能够成功地更改消防商店中的用户角色,但正如您所见,当用户登录数据库时,值将设置为默认值,但我不希望这样。所以,我的问题是如何检查用户是第一次登录还是返回用户。
如果用户返回,那么我不想在 Fire 商店中重置用户数据,如果用户是新用户,则在 Fire 商店中使用默认值创建文档。
结论,我如何检查当用户使用谷歌登录时,用户是现有用户还是新用户?

最佳答案

您可以通过User Credential查看用户是新用户还是之前注册的用户并通过您可以检索authResult.additionalUserInfo.isNewUser如果用户之前没有注册过。
您可以使用以下代码:

 Future<UserCredential> signInWithGoogle(BuildContext context) async {

FirebaseAuth _auth = FirebaseAuth.instance;
// Trigger the authentication flow
final GoogleSignInAccount googleUser = await GoogleSignIn().signIn();

// Obtain the auth details from the request
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;

// Create a new credential
final GoogleAuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);

final UserCredential authResult =
await _auth.signInWithCredential(credential);

final User user = authResult.user;

///Her to check isNewUser OR Not
if (authResult.additionalUserInfo.isNewUser) {
if (user != null) {
//You can her set data user in Fire store
//Ex: Go to RegisterPage()
}

}
} else {

//Ex: Go to HomePage()
}

return await FirebaseAuth.instance.signInWithCredential(credential);
}

关于android - 如何在flutter中使用firebase登录谷歌时检查用户是新用户还是现有用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64619174/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com