0

这是我的谷歌登录代码..

             onPressed: () async{
                final GoogleSignInAccount newuser= await GoogleSignIn().signIn();
                final  GoogleSignInAuthentication newuserauth= await 
         googleUser.authentication;
                final GoogleAuthCredential cred= GoogleAuthProvider.credential(accessToken: 
                 newuserauth.accessToken,idToken: newuserauth.idToken);
                await FirebaseAuth.instance.signInWithCredential(cred);
              },

我得到的错误如下..

        error: A value of type 'OAuthCredential' can't be assigned to a variable of type 
        'GoogleAuthCredential'. (invalid_assignment at [firebase] lib\firstpage.dart:147)

        error: Undefined name 'googleUser'. (undefined_identifier at [firebase] 
            lib\firstpage.dart:145)
         error: A value of type 'GoogleSignInAccount?' can't be assigned to a variable of type 
        'GoogleSignInAccount'. (invalid_assignment at [firebase] lib\firstpage.dart:144)

这些是我的 pubspec.yaml 中的依赖项。

      dependencies:
        flutter:
          sdk: flutter
           firebase_auth: ^3.2.0
           firebase_core : ^1.10.0
           flutter_spinkit: ^5.1.0
           cloud_firestore: ^3.1.0
           google_sign_in: ^5.2.1
4

1 回答 1

1

您的代码中存在多个问题,如下所示:

第 2 行:GoogleSignIn().signIn()返回GoogleSignInAccount?这意味着它可能为空,但您正在使用GoogleSignInAccount这意味着它不能为空,所以将其更改为(这是您遇到的最后一个错误):

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

第 3 行和第 4 行:您使用的变量名newuser没有googleUser更改其中之一(第二个错误)

第 5 行和第 6 行:不GoogleAuthProvider.credential(..)返回,这是您遇到的第一个错误。OAuthCredentialGoogleAuthCredential

但是,final您不需要指定变量类型,这是 Dart 的优势之一。

此外,您会收到错误,newuser.authentication因为如前所述,newuser 可能为 null,因此您无法访问authentication……我喜欢这样做的方式,因为我不喜欢处理 null 值是从如果它为空,则在使用它之前的函数。

所以整个代码将是(我添加了类型,以便您可以看到差异,但您不需要它们):

final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
if (googleUser == null) return null;
  
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final OAuthCredential credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );
await FirebaseAuth.instance.signInWithCredential(credential);
于 2021-11-25T07:34:28.033 回答