Home > Software engineering >  Flutter: GoogleSignInAccount The property 'authentication' can't be unconditionally a
Flutter: GoogleSignInAccount The property 'authentication' can't be unconditionally a

Time:01-14

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

CodePudding user response:

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();

  •  Tags:  
  • Related