简体   繁体   中英

A value of type 'GoogleSignInAccount?' can't be assigned to a variable of type 'GoogleSignInAccount'

This is 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;
  }
}


This is the suggestion that flutter provides, but I don't know what to do:

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'.

How can I solve this issue?

Thanks for any help you can provide

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM