firebase 如何重定向到另一个页面后,谷歌登录在Flutter

q8l4jmvw  于 2022-12-24  发布在  Flutter
关注(0)|答案(4)|浏览(195)

我仍然是新的Flutter,我想知道如何重定向到另一个页面后,登录到我的应用程序使用谷歌登录,有人能帮助这件事吗?这里的代码。我不知道在这种情况下重定向到另一个页面。谢谢

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

class GoogleSignInProvider extends ChangeNotifier {
  final googleSignIn = GoogleSignIn();
  GoogleSignInAccount? _user;
  GoogleSignInAccount get user => _user!;

  Future googleLogin() async{
    final googleUser = await googleSignIn.signIn();
    if (googleUser == null) return;

    _user = googleUser;
 
    final googleAuth = await googleUser.authentication;

    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    await FirebaseAuth.instance.signInWithCredential(credential);
    notifyListeners();
  }
}
egdjgwm8

egdjgwm81#

这是我的

class Authentication {
    static Future<User?> signInWithGoogle() async {
    FirebaseAuth auth = FirebaseAuth.instance;
    User? user;

    final GoogleSignIn googleSignIn = GoogleSignIn();

    final GoogleSignInAccount? googleSignInAccount =
await googleSignIn.signIn();

if (googleSignInAccount != null) {
  final GoogleSignInAuthentication googleSignInAuthentication =
  await googleSignInAccount.authentication;

  final AuthCredential credential = GoogleAuthProvider.credential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken,
  );

  try {
    final UserCredential userCredential =
    await auth.signInWithCredential(credential);

    user = userCredential.user;
  } on FirebaseAuthException catch (e) {
    if (e.code == 'account-exists-with-different-credential') {
      Get.showSnackbar(const GetSnackBar(
        message: "You already have an account with this email. Use other login method.",
        duration: Duration(seconds: 3),
      ));
    }
    else if (e.code == 'invalid-credential') {
      Get.showSnackbar(const GetSnackBar(
        message: "Invalid Credential!",
        duration: Duration(seconds: 3),
      ));
    } else if (e.code == 'wrong-password') {
      Get.showSnackbar(const GetSnackBar(
        message: "Wrong password!",
        duration: Duration(seconds: 3),
      ));
    }
  } catch (e) {
    Get.showSnackbar(const GetSnackBar(
      message: "Unknown Error. Try again later",
      duration: Duration(seconds: 3),
    ));
  }
}

return user;
  }
}

然后在登录屏幕中,如果您成功登录,则可以添加此内容以进行导航:

import 'your/google/sign/in/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';

class Login {
    User? user;
    user = await Authentication.signInWithGoogle();
    if (user != null) {
      Navigator.pushReplacement<void, void>(
    context,
    MaterialPageRoute<void>(
      builder: (BuildContext context) => const PageAfterSignIn(),));
    } else {
      
    }
}

我基于this article编写我的

s4n0splo

s4n0splo2#

方法FirebaseAuth.instance.signInWithCredential返回一个Future(Promise),它可以是用户是否成功登录。

final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
final user = userCredential.user;

如果您想移动到差异屏幕,您可以只使用Navigator.push方法:

Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => //YOUR SCREEN HERE),
  );

Documentation

ny6fqffe

ny6fqffe3#

Firebase auth提供了一个authStateChanges(),这是一个Stream,因此每次新用户登录或注销时,它都会被触发,在您的代码中调用:

await FirebaseAuth.instance.signInWithCredential(credential);

如果运行成功,将触发它。
您可以使用StreamBuilder来侦听authStateChanges()流,如下例所示:

StreamBuilder<User>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          User user = snapshot.data;
          if (user == null) {
            return LoginPage();
          }
          return HomePage();
        } else {
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
      },
    );

此微件应在应用的顶层运行(例如,在应用的homeMaterialApp中使用它)
最初,当没有用户登录时,firebase的User将是null,因此它将重定向到LoginPage
在成功登录的操作(如代码中的FirebaseAuth.instance.signInWithCredential(credential);)上,User将包含一些数据,但它不是null,因此StreamBuilder将收到通知,并显示HomePage()页面。

olhwl3o2

olhwl3o24#

您可以在登录页面点击谷歌登录按钮后进入下一个屏幕,如下代码

onTap: () async {
            GoogleSignInProvider. googleLogin().then((isSuccess) {
              if (isSuccess) {
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (context) => HomePage()));
              }
            });
          },

相关问题