This is my code for google sign-in ..
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);
},
And the errors i am getting are as follows..
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)
These are the dependencies in my 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
CodePudding user response:
There is multiple problems in you code as follows:
Line 2 : GoogleSignIn().signIn()
returns GoogleSignInAccount?
which mean it could be null but you're using GoogleSignInAccount
which mean it can't be null,,, so change it to (This is the last error you got):
final GoogleSignInAccount? newuser= await GoogleSignIn().signIn();
Line 3 & 4: You used the variable name newuser
not googleUser
change one of them (the second error)
Line 5 & 6: GoogleAuthProvider.credential(..)
returns OAuthCredential
not GoogleAuthCredential
and that is the first error you got.
However, with final
you don't need to specify the variable type which is one of the Dart advantages.
Moreover, you'll get error on newuser.authentication
because newuser, as mentioned before, could be null so you can't access authentication
... the way I love to do it, because I don't like to deal with null values is to return from the function before using it if its null.
So the whole code would be (I added the types so you could see the difference, but you don't need them ):
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);