[英]Not selecting an account in google account login in flutter bug on still entering the home page of the app
So implementing this google account sign in feature for the app that I'm building and i encounter this bug on which if i dont select an account like click outside the pop up selection of google account or press the back button i can still enter the home page of the app, i dont know how to catch this error please help me, this is my code因此,为我正在构建的应用程序实现这个谷歌帐户登录功能,我遇到了这个错误,如果我没有选择一个帐户,比如在谷歌帐户的弹出选择之外点击或按后退按钮,我仍然可以进入主页应用程序的页面,我不知道如何捕捉这个错误请帮助我,这是我的代码
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
primary: Colors.white,
onPrimary: Colors.black,
minimumSize: const Size(double.infinity,50),
),
icon: const FaIcon(FontAwesomeIcons.google, color: Colors.red,),
label: const Text("Login using Gmail"),
onPressed: () async{
try {
var result = await FirebaseServices().signInWithGoogle()..catchError((onError) => print(onError.toString()));
if (result == null) return;
Navigator.push(context, MaterialPageRoute(builder: (context)=> const HomePage()));
// if (FirebaseServices().signInWithGoogle() == null) return;
// Navigator.push(context,MaterialPageRoute(builder: (context)=> const HomePage()));
}
on FirebaseAuthException catch (e){
print(e.message);
throw e;
}
},
),
and here's my main.dart code这是我的 main.dart 代码
class _MyAppState extends State<MyApp> {
late StreamSubscription<User?> user;
@override
void initState() {
super.initState();
user = FirebaseAuth.instance.authStateChanges().listen((user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});
}
@override
void dispose() {
user.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute:
// "/loginpage",
FirebaseAuth.instance.currentUser == null ? LoginPage.id : HomePage.id,
routes: {
// "/homepage": (context)=> const HomePage(),
// "/loginPage" : (context)=> const LoginPage(),
LoginPage.id: (context) =>const LoginPage(),
HomePage.id: (context) => const HomePage(),
},
home: const LoginPage(),
);
}
}
and here's my google service code这是我的谷歌服务代码
class FirebaseServices{
final _auth = FirebaseAuth.instance;
final _googleSignIn = GoogleSignIn();
final _formkey = GlobalKey<FormState>();
var context;
signInWithGoogle() async{
//if(_formkey.currentState!.validate()){
try{
final GoogleSignInAccount? googleSignInAccount =
await _googleSignIn.signIn().catchError((onError)=>print(onError));
//plugin
if (googleSignInAccount == null) return null;
// ignore: unused_local_variable
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
//end plugin
if (googleSignInAccount!=null){
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential authCredential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken);
await _auth.signInWithCredential(authCredential)
.then((value) => {
postDetailsToFirestore(),
}
).catchError((e)
{
Fluttertoast.showToast(msg: e!.message);
});
}
}on FirebaseAuthException catch (e){
print(e.message);
throw e;
//}
}
}
signOut() async{
await _auth.signOut();
await _googleSignIn.signOut();
}
postDetailsToFirestore() async{
//calling firestore,calling user model, sending values
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
User? user = _auth.currentUser;
UserModel userModel = UserModel();
//writing values
userModel.email = user!.email;
userModel.uid = user.uid;
userModel.fullname = user.displayName;
userModel.profileimage=user.photoURL;
await firebaseFirestore
.collection("Users")
.doc(user.uid)
.set(userModel.toMap());
}
}
here's a video about the bug这是一个关于这个错误的视频
here's the newest bug
这是最新的错误
The logic in your "onPressed" login button should only authenticate, but not push the homePage. “onPressed”登录按钮中的逻辑应该只进行身份验证,而不是推送主页。
The recommended solution is to have a "landingPage" listening to FirebaseAuth.instance.authStateChanges() and checking the user.推荐的解决方案是让“landingPage”监听 FirebaseAuth.instance.authStateChanges() 并检查用户。 If it is null, push AuthenticationPage, otherwise homePage.
如果为null,则推送AuthenticationPage,否则为homePage。
You can find more details below:您可以在下面找到更多详细信息:
https://firebase.google.com/docs/auth/flutter/start https://firebase.google.com/docs/auth/flutter/start
https://pub.dev/packages/google_sign_in/example (this example listens to a different stream) but has the same logic https://pub.dev/packages/google_sign_in/example (此示例监听不同的流)但具有相同的逻辑
When you are first calling the FirebaseServices.signInWithGoogle().catchError();
当您第一次调用
FirebaseServices.signInWithGoogle().catchError();
You are awaiting an error result.您正在等待错误结果。 I would suggest you that you call it in this way:
我建议你这样称呼它:
try {
// Here, we use the .. (cascade) operator, which will give us the
// reference to the correct future that signInWithGoogle() returns.
var result = await FirebaseServices().signInWithGoogle()..catchError((onError) => print(onError.toString()));
// If we didn't sign in, then do not proceed to the home screen
if (result == null) return;
// We push a replacement route so that when the user
// consecutively presses the back button, he doesn't reach the
// login screen before exiting the app.
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=> const HomePage()));
} on FirebaseAuthException catch(e) {
print(e.message);
// Do not throw an exception in your production app. It will make the app crash. Instead,
// display it to the user with a Dialog.
throw e;
}
If my answer was helpful, please mark my answer as Correct.如果我的回答有帮助,请将我的回答标记为正确。 Thank you!
谢谢!
Also, I recommend you to follow @Saichi Okuma's answer, as that is the correct approach to signing-in the user in a production app.另外,我建议您遵循@Saichi Okuma 的回答,因为这是在生产应用程序中登录用户的正确方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.