分配“GoogleSignInAccount”时出错?到 Flutter 身份验证中的“GoogleSignInAccount”

问题描述 投票:0回答:1

我正在我的 Flutter 应用程序中将 Google 登录与 Firebase 身份验证集成。当尝试将

GoogleSignIn().signIn(
) 的结果分配给
GoogleSignInAccount
变量时,我遇到类型不匹配错误。这是我的代码的相关部分:

// ignore: import_of_legacy_library_into_null_safe
import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';

Future<Map<String, dynamic>> signInWithGoogle() async {
  final GoogleSignInAccount googleUser = await GoogleSignIn().signIn();
  final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
  final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );

  return {
    "email": googleUser.email,
    "photoUrl": googleUser.photoUrl,
    "credentials": await FirebaseAuth.instance.signInWithCredential(credential),
  };
}

Future<bool> signInWithEmail(String email, String password) async {
  try {
    FirebaseAuth.instance.
    signInWithEmailAndPassword(email: email, password: password);
    return true;
  } on FirebaseAuthException catch(e){
    print(e.code);
    return false;
  }
}



Future<bool> signUpWithEmail(String email, String password) async {
  try {
    FirebaseAuth.instance.
    createUserWithEmailAndPassword(email: email, password: password);
    return true;
  } on FirebaseAuthException catch(e){
    print(e.code);
    return false;
  }
}


Flutter的建议是:

“GoogleSignInAccount?”类型的值无法分配给“GoogleSignInAccount”类型的变量。 尝试更改变量的类型,或将右侧类型转换为“GoogleSignInAccount”。

我尝试将变量转换为不可空类型,但仍然面临问题。如何正确分配“GoogleSignInAccount”类型的值?在此上下文中的“GoogleSignInAccount”类型的变量?

flutter dart firebase-authentication google-signin
1个回答
1
投票

正如错误所述,

GoogleSignIn().signIn()
返回您
GoogleSignInAccount?
,这意味着它可能是
null
,并且您不能将其传递给变量类型
GoogleSignInAccount
。您需要将
googleUser
的类型更改为
GoogleSignInAccount?

final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

之后您需要将

signInWithGoogle
中的返回地图更改为:

final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication;

...
return {
    "email": googleUser?.email ?? '',
    "photoUrl": googleUser?.photoUrl ?? '',
    "credentials": await FirebaseAuth.instance.signInWithCredential(credential),
  };

我所做的是在

?
上使用
googleUser
,并设置默认值 (
' '
),以防 googleUser 为
null
。您也需要对
credential
重复此操作,并为其提供对其有利的默认值,以防它也获得
null

© www.soinside.com 2019 - 2024. All rights reserved.