'OAuthCredential' 类型的值不能分配给 'GoogleAuthCredential' 类型的变量

A value of type 'OAuthCredential' can't be assigned to a variable of type 'GoogleAuthCredential'

这是我的 google 登录代码..

             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

您的代码存在多个问题如下:

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

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

第 3 & 4 行:您使用了变量名 newuser 而不是 googleUser 更改其中一个(第二个错误)

第 5 行和第 6 行:GoogleAuthProvider.credential(..) returns OAuthCredential 而不是 GoogleAuthCredential,这是您遇到的第一个错误。

然而,使用 final 你不需要指定变量类型,这是 Dart 的优势之一。

此外,您会在 newuser.authentication 上遇到错误,因为如前所述,newuser 可能为空,因此您无法访问 authentication... 我喜欢这样做的方式,因为我不喜欢处理 null 值是在使用它之前从函数 return 如果它的 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);