I'm integrating Google sign-in with Firebase authentication in my Flutter app. When trying to assign the result of GoogleSignIn().signIn(
) to a GoogleSignInAccount
variable, I encounter a type mismatch error. Here's the relevant part of my code:
// 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's suggestion is:
A value of type 'GoogleSignInAccount?' can't be assigned to a variable of type 'GoogleSignInAccount'. Try changing the type of the variable, or casting the right-hand type to 'GoogleSignInAccount'.
I've attempted to cast the variable to the non-nullable type but still face issues. How can I correctly assign a value of type 'GoogleSignInAccount?' to a variable of type 'GoogleSignInAccount' in this context?
As the error said, GoogleSignIn().signIn()
returns you GoogleSignInAccount?
that means it could be null
and you can't pass it to variable type GoogleSignInAccount
. You need to change googleUser
's type to GoogleSignInAccount?
.
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
after that you need to change your return map in signInWithGoogle
to this:
final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication;
...
return {
"email": googleUser?.email ?? '',
"photoUrl": googleUser?.photoUrl ?? '',
"credentials": await FirebaseAuth.instance.signInWithCredential(credential),
};
what I did is that use ?
on googleUser
, and set the default value (' '
) incase that googleUser was null
. you need to repeat this for credential
too and provide it default value that good for it incase it get null
too.