对于已登录的用户
Future<String> signInWithGoogle() async {
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final AuthResult authResult = await _auth.signInWithCredential(credential);
final FirebaseUser user = authResult.user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final FirebaseUser currentUser = await _auth.currentUser();
assert(user.uid == currentUser.uid);
if(authResult.additionalUserInfo.isNewUser == true){
InsertNewUserDetails(user.displayName,user.email,user.photoUrl,user.phoneNumber);
}
if(authResult.user != null){
email = user.email;
name = user.displayName;
imageUrl =user.photoUrl;
globalInstance.isLoggedIn = true;
print(globalInstance.isLoggedIn);
}
return 'signInWithGoogle succeeded: $user';
}
这是首次登录“登录页面”以检查是否已登录的帐户
class MyApp extends StatelessWidget {
@override
String strinbggg;
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.teal,
body: StreamBuilder<FirebaseUser>(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (BuildContext context, snapshot) {
if (snapshot.hasData && (!snapshot.data.isAnonymous)) {
// return Text('${snapshot.hasData}');
return Homepage();
} else {
// return SafeArea(
// maintainBottomViewPadding: true,
// child: Text('aasdasdfasfdh : ${snapshot.data.email}',style: TextStyle(color: Colors.black54),));
return LoginPage();
}
},
),
),
);
}
}
首次使用google登录时会起作用。当我关闭应用程序并重新启动时,它将重定向到首页,但用户个人资料详细信息(如displayName,电子邮件返回空值)
signInwithgoogle()首次用于将用户详细信息存储在Firestore中以及从此处设置的用户详细信息登录
MyApp是应用程序的起点,它将检查用户是否已登录
答案 0 :(得分:0)
我建议您检查用户是否已经登录或未使用方法
bool isSignedIn = await _googleSignIn.isSignedIn();
,如果用户已登录,则使用来获取凭据
user = await _auth.currentUser();
启动应用程序时。如果您尚未登录,请显示登录页面。任何示例都将如下所示
final auth = FirebaseAuth.instance;
class MyApp extends StatelessWidget {
@override
String strinbggg;
Widget build(BuildContext context) {
return MaterialApp(
home: (_isSignedIn() == true ? new Homepage() : new LoginPage()));
}
bool _isSignedIn() async {
bool isSignedIn = await _googleSignIn.isSignedIn();
if(isSignedIn){
GoogleSignInAccount user = await auth.currentUser;
//You can store this in your state.
}
return !(user == null && auth.currentUser == null);
}
}
请注意,这是一个由编辑器编写的代码,未经测试,您必须进行调整。