简体   繁体   English

在仍然进入应用程序主页时,在颤振错误中未选择谷歌帐户登录中的帐户

[英]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.

相关问题 使用谷歌账户和firebase集成应用程序登录 - App login with google account and firebase integration Flutter:Google 登录弹出窗口不会出现在 select 帐户中 - Flutter : Google Login pop up wont appear to select an account 在 flutter 中使用 google 帐户登录后提高 google 帐户图像的质量 - Improve the quality of the google account image after login using google account in flutter 登录 firebase 帐户失败会引发异常并停止 Flutter 应用程序 - Failing login to firebase account throws exception and stops flutter app facebook 登录仅显示以前在 flutter 应用程序中登录的帐户 - facebook login showing only previous logged in account in flutter app 从 Flutter 应用程序打开 Instagram 特定帐户页面 - Open instagram particular account page from flutter app 在 Flutter 应用程序中使用用户的 Google 帐户个人资料图片 - Using user's Google account profile picture in Flutter app Flutter登录成功后如何返回app首页 - How to get back to app home page after successful login in Flutter 在 Flutter 应用程序(Google + FireBase)上跳过登录页面 - Skip login page on Flutter app(Google + FireBase) 在 flutter 应用程序 android 中,我无法使用 flutter 应用程序注册帐户,只是登录,错误说“错误的 Z0C83F57C786A0B4A39EFAB23731CEB7”? - in flutter app android I cant register account with flutter app just login ,, the error said “wrong email or password”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM