尝试使用谷歌登录但总是返回 null

时间:2021-04-03 02:52:28

标签: firebase flutter firebase-authentication

嘿,伙计们,我试图在 flutter 中使用 firebase 登录谷歌,但它总是在下一页返回 null

使用google登录后如何在下一页获取当前用户

我已经与 firebase 连接并生成了 sha-1 和 sha-256

这是代码

login_screen.dart

MaterialButton(
    height: 50,
    minWidth: double.maxFinite,
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        FaIcon(FontAwesomeIcons.google, color: Colors.blue,),
        SizedBox(width: 10,),
        Text('Sign In With Google', style: TextStyle(color: Colors.blue),),
      ],
    ),
    elevation: 0,
    onPressed: () async {
      setState(() {
        _isSigningIn = true;
      });

      try {
        final user = await googleSignIn.signIn();
        final googleAuth = await user.authentication;

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

        final googleAccount = await FirebaseAuth.instance.signInWithCredential(credential);

        if(googleAccount != null) {
          Navigator.pushReplacementNamed(context, HomeScreen.id);
        }
      } catch (e) {
        final snackbar = SnackBar(content: Text(e.toString()));
        _scaffoldKey.currentState.showSnackBar(snackbar);
      } finally {
        setState(() {
          _isSigningIn = false;
        });
      }
    },
  ),

home_screen.dart

class HomeScreen extends StatefulWidget {
  static const String id = 'HomeScreen';

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final _auth = FirebaseAuth.instance;
  User _currentUser;

  void getCurrentUser() async {
    try {
      var currentUser = await _auth.currentUser;

      if (currentUser != null) {
        _currentUser = currentUser;
      }
    } catch(e) {
      print(e);
    }
  }

  @override
  void initState() {
    super.initState();
    getCurrentUser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_currentUser.email),
      ),
    );
  }
}

谢谢...................................................... ......................................!

1 个答案:

答案 0 :(得分:0)

这一行是一个异步函数,正是因为这个原因,你收到null,你必须加一个await。

final googleAccount = await FirebaseAuth.instance.signInWithCredential(credential);

除此之外,要访问当前用户的信息,您必须这样做。

googleAccount.user