flutterdartauthenticationgooglesigninaccount

Flutter: GoogleSignInAccount The property 'authentication' can't be unconditionally accessed because the receiver can be 'null'


I'm new to flutter. Am practicing google account log in. When I define GoogleSignInAccount, there is an error: "A value of type 'GoogleSignInAccount?' can't be assigned to a variable of type 'GoogleSignInAccount'."

final GoogleSignInAccount googleUser = await _googleSignIn.signIn();

Other people saying that we can use '?' to solve this problem. It works. However, another issue pop up: "The property 'authentication' can't be unconditionally accessed because the receiver can be 'null'."

final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

Any advice would be great. ty


Solution

  • You get that warning because googleUser has a nullable type (GoogleSignInAccount?) in order to use it in googleAuth you can mark it with a bang (null-aware) operator like this googleUser!.authentication;. However, only use that approach if you are 100% certain this will never be null, in which case you could simply use a non-nullable type (without the "?") if possible.

    Alternatively, you can use control flow statements to only initialize googleAuth once googleUser is initialized with a non-null value.

    For example a null-check like this:

    if(googleUser !=null) {
       final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
    }
    

    More context:

    The reason why you get the error: "A value of type 'GoogleSignInAccount?' can't be assigned to a variable of type 'GoogleSignInAccount'." is that _googleSignIn.signIn(); has a nullable return type of 'GoogleSignInAccount?'(because it can fail and don´t return a user), hence you cant assign it to a non-nullable variable with the type 'GoogleSignInAccount'.

    FYI: It most likely makes more sense to add the null check around the _googleSignIn.signIn();